#!/usr/bin/perl -w
use strict;
use Getopt::Long;
our %options=qw;
verbose		0
path		root/backup
incfile		incfile
ftp		1
compression	z
;;
my @backlog=(2,5,7,24);
my @maxsize=(40000, 30000, 10000, 1000);
my @daysback=(32, 8, 6, 1);
my @dirs=qw"etc boot usr/local root home srv var";
my @excl=($options{path}, "var/log", "var/lib/locatedb", "home/mld/mldonkey-2.5-3/incoming", "home/mld/mldonkey-2.5-3/temp", "home/bernhard/code/rpm");
#preprocessing
my $dirs=join " ",@dirs;
foreach(@maxsize){$_*=2}
my @exclargs;


chdir "/";
umask 077;

my @options=qw(ftp! incremental! type=i verbose|v path=s compression=s outputfile|o:s exclude=s@);
if(!GetOptions(\%options, @options)) {die "invalid option on commandline. @ARGV\n"}

sub getbackupfile($$) { my($type,$n)=@_;
	my $ext=($options{compression} eq "j")?"bz2":"gz";
	if($backlog[$type]>9 && $n<=9) { $n="0$n" }
	$options{incremental}+=0;
	return $options{path}."/backup-$type-$options{incremental}-$n.tar.$ext";
}

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday)=gmtime();
my $type=$options{type};
my $n;
if($options{verbose}) {
  print "wday: $wday mday: $mday hour: $hour\n";
}
if(!defined($type)) {
	if($wday==6) { 
		$type=1;
		if($mday<8) { $type=0 }
	} elsif($hour==3) { $type=2 }
	else { $type=3 }
}
if($type==0) {$n=$mon}
elsif($type==1) {$n=int($yday/7)}
elsif($type==2) {$n=$wday}
else {$n=$hour}
if(!defined($options{incremental})) {$options{incremental}=$type>1}
if($options{verbose}) {
  print ("Starting backup type $type ".($options{incremental}?"incremental":"full")."\n");
  print ("omitting files > $maxsize[$type]\n");
}

my $lastn=($n-1)%$backlog[$type];
$n%=$backlog[$type];
my $outfile=getbackupfile($type,$n);
my $reffile=getbackupfile($type,$lastn);
my @check=();
if($options{outputfile}) {
  $outfile=$options{outputfile};
}
#if(-e $reffile) {push(@check, "-newer", $reffile)} # this creates minimal incremental backups

$options{incfile}=$options{path}."/".$options{incfile}.$type;
foreach(@excl, @{$options{exclude}}) { push(@exclargs, "--exclude", $_); }

# for type 2 and 3 we do incremental backups
if($options{incremental}) {
	if($type==2) { $daysback[$type]=$wday+1 }
	my $check=join " ", @check;
	system("find $dirs -type f -mtime -$daysback[$type] $check -size -$maxsize[$type] -print0 > $options{incfile}");
#	if(-s $options{incfile}) {} check for empty file and {exit 0}
	system("tar", "-c$options{compression}f", $outfile, "--null", "-T", $options{incfile}, @exclargs);
}
else {
	system("find $dirs -type f -size +$maxsize[$type] -o -type s > $options{incfile}");
	system("tar", "-c$options{compression}f", $outfile, "-X", $options{incfile}, @exclargs, @dirs);
}
#print $outfile, "\n";
if($options{ftp}) {
	system(qw"ncftpput -V -f /root/backup/backupftp /", $outfile);
}
#if($type>1) {unlink $outfile}

exit 0;

