#!/usr/bin/perl

# 複数ホストからバックアップし、一定時間以上古い履歴は削除する
#
# - バックアップ元、先共に rdiff-backup がインストールされている必要がある (yum install rdiff-backup)
# - このスクリプトは、バックアップ先のcronで設定する
#   - # cp rdiff-backup.pl /etc/cron.daily/rdiff-backup.pl
#   - # chmod 755 /etc/cron.daily/rdiff-backup.pl
# - パスワードが必要無いようにrootユーザのssh公開鍵認証は済ませておく
#   - http://www.atmarkit.co.jp/flinux/rensai/linuxtips/447nonpassh.html

# バックアップ元
# - ディレクトリ末尾には'/'不要
# - タブ区切りでオプション指定(除外指定:--exclude 等)
my(@BACKUP_FROM) = (
	'192.168.0.100::/home	--exclude /home/hoge',
	'192.168.0.100::/etc',
	'192.168.0.101::/var/www/html',
	'192.168.0.101::/etc',
	);

# バックアップ先
my $BACKUP_TO='/mnt/backup/backup';

# 2週間より前の差分は削除する
my $DELETE_OPTION='2W';

# rdiff-backupコマンドパス
my $RDIFF_BACKUP='/usr/bin/rdiff-backup';

my $DEBUG=0;

use File::Path;

main();
exit;

sub main
{
	$SIG{'PIPE'} = $SIG{'INT'} = $SIG{'HUP'} = $SIG{'QUIT'} = $SIG{'TERM'} = "sigexit";

	unless(-e $RDIFF_BACKUP){
		print STDERR "Can't find rdiff-backup : $RDIFF_BACKUP\n";
		exit(1);
	}
	
	$BACKUP_TO =~ s/\/+$//;
	
	for my $from (@BACKUP_FROM){
		$from =~ s/\/+$//;
		backup($from, $BACKUP_TO);
	}
}

sub backup
{
	my($from, $to) = @_;
	my($tmp_from, @from_options) = split("\t", $from);
	my($from_host, $from_path) = split("::", $tmp_from);
	my $to_path = $to . '/' . $from_host . $from_path;
	
	unless(-d $to_path){
		mkpath([$to_path], 0, 0700);
	}
	unless(-d $to_path){
		print STDERR "Cant' create dir : $to_path";
		return;
	}
	
	$cmd_backup = sprintf('%s %s "%s" "%s"', $RDIFF_BACKUP, join(' ', @from_options), $tmp_from, $to_path);
	$cmd_remove = sprintf('%s --force --remove-older-than %s "%s"', $RDIFF_BACKUP, $DELETE_OPTION, $to_path);
	if($DEBUG){
		printf "$cmd_backup\n";
		printf "$cmd_remove\n";
	}else{
		system("$cmd_backup");
		system("$cmd_remove");
	}
}

sub sigexit
{
	my($sig) = @_;
	print STDERR "Caught a SIG$sig .\n";
	exit(1);
}

# EOF
