| 1 | #! /usr/bin/env php |
|---|
| 2 | <?php |
|---|
| 3 | |
|---|
| 4 | require_once(dirname($argv[0]) . "/utilities.php"); |
|---|
| 5 | |
|---|
| 6 | $home_dir = exec('echo $HOME'); |
|---|
| 7 | define("IA_BACKUP_REPO_DIR", "$home_dir/backup/infoarena"); |
|---|
| 8 | define("IA_BACKUP_SSL_CERT", "$home_dir/.ssh/ia-backup"); |
|---|
| 9 | |
|---|
| 10 | function week_timestamp() { |
|---|
| 11 | return date("YW"); |
|---|
| 12 | } |
|---|
| 13 | |
|---|
| 14 | function check_env() { |
|---|
| 15 | log_assert(is_dir(IA_BACKUP_REPO_DIR)); |
|---|
| 16 | log_assert(file_exists(IA_BACKUP_SSL_CERT)); |
|---|
| 17 | log_assert(exec('which rsync'), "Please install rsync"); |
|---|
| 18 | } |
|---|
| 19 | |
|---|
| 20 | function exec_rsync($source_dir, $target_dir, $delete_extraneous=false) { |
|---|
| 21 | log_print("rsync $source_dir -> $target_dir"); |
|---|
| 22 | $delete_arg = $delete_extraneous ? '--delete' : ''; |
|---|
| 23 | $cmd = sprintf("rsync -avC {$delete_arg} --rsh='ssh -p 21883 -i %s' " |
|---|
| 24 | ."backup@infoarena.ro:%s %s/%s", IA_BACKUP_SSL_CERT, $source_dir, |
|---|
| 25 | IA_BACKUP_REPO_DIR, $target_dir); |
|---|
| 26 | system($cmd); |
|---|
| 27 | } |
|---|
| 28 | |
|---|
| 29 | function sync_attachments() { |
|---|
| 30 | $new_snapshot = week_timestamp(); |
|---|
| 31 | if (!is_dir(IA_BACKUP_REPO_DIR."/attach")) { |
|---|
| 32 | mkdir(IA_BACKUP_REPO_DIR."/attach"); |
|---|
| 33 | } |
|---|
| 34 | $last_snapshot = exec(sprintf("ls -1 '%s'", |
|---|
| 35 | IA_BACKUP_REPO_DIR."/attach")); |
|---|
| 36 | if ($last_snapshot && $last_snapshot != $new_snapshot) { |
|---|
| 37 | log_print("Duplicating last snapshot with hard links " |
|---|
| 38 | ."($last_snapshot -> $new_snapshot)"); |
|---|
| 39 | system(sprintf("cp -alr %s %s", |
|---|
| 40 | IA_BACKUP_REPO_DIR."/attach/".$last_snapshot, |
|---|
| 41 | IA_BACKUP_REPO_DIR."/attach/".$new_snapshot)); |
|---|
| 42 | } |
|---|
| 43 | log_print("Syncing last snapshot"); |
|---|
| 44 | exec_rsync('attach-live/', "attach/$new_snapshot/", true); |
|---|
| 45 | } |
|---|
| 46 | |
|---|
| 47 | function main() { |
|---|
| 48 | global $argv; |
|---|
| 49 | check_env(); |
|---|
| 50 | exec_rsync('ia-backup/', 'archive/'); |
|---|
| 51 | sync_attachments(); |
|---|
| 52 | } |
|---|
| 53 | |
|---|
| 54 | main(); |
|---|
| 55 | |
|---|
| 56 | ?> |
|---|