#!/usr/bin/perl
use strict;

my $DEBUG = 0;
my $MYSQLDIR = "/var/lib/mysql";
my $mustdump = 0;
my $dblastupdated = 0;
my @safetouseolddumps = qw{ MYD frm MYI opt CSV };
my $bestfilesofar = "";

unless ($ARGV[0]) {
  print "\n\tUsage = $0 <db> <file> <mysqldump-options>\n\tExample: $0 username_blah /backup3/cpbackup/daily/username/mysql/username_blah.sql\n\n";
  exit;
}

$0 = "mysqldumper";

my $db = shift(@ARGV);
my $file = shift(@ARGV);
print "\n\nDB: $db\nFILE: $file\n" if $DEBUG;
print "OPTIONS: ".join(" ", @ARGV)."\n" if $DEBUG;

#check that the database in question is ok to decide upon due to timestamps
#eg, is it all myisam?
#while we are at it, get the most recent timestamp on that
opendir(DIR, "$MYSQLDIR/$db") or print "Unable to find dir. Dumping db with default params.\n" and exit 1;
my @entries = readdir(DIR);
close(DIR);
FILECHECK: foreach my $file (@entries){
   next if $file =~ m/^\./;
   my @attrib = lstat("$MYSQLDIR/$db/$file");
   $dblastupdated = $attrib[9] if $attrib[9] > $dblastupdated;
   my $extension = substr($file,(length($file) - 3), 3);
   foreach(@safetouseolddumps){
     next FILECHECK if $extension eq $_;
   }
   print "non-safe file fourd, we must dump: $file\n" if $DEBUG;
   $mustdump = 1;
   last;
}
unless($mustdump){
  print "db last updated: ".localtime($dblastupdated)."\n" if $DEBUG;
  my ($username,$blah) = split('_', $db);
  foreach my $bdir (qw{ /backup /backup1 /backup2 /backup3 /backup4 /backup5 /backup6 /backup7 /backup8 }){
    next unless -e "$bdir/cpbackup";
    foreach(qw{monthly weekly daily seed}){
      my $backupfiletocheck = "$bdir/cpbackup/$_/$username/mysql/$db.sql";
      if(-e $backupfiletocheck){
        my @attrib = lstat($backupfiletocheck);
        if($attrib[9] > $dblastupdated){
          my $last = `tail -1 $backupfiletocheck`;
          if( $last =~ m/Dump completed on/){
            print "found suitable file: $backupfiletocheck ".localtime($attrib[9])."\n" if $DEBUG;
            $bestfilesofar = $backupfiletocheck;
            $dblastupdated = $attrib[9];
          }
        }
      }
    }
  }
}




unless($bestfilesofar ne ""){
  print "==== WE ARE DUMPING! ====\n" if $DEBUG;
  exit 1;
}else{
  print "best file found: $bestfilesofar\n" if $DEBUG;

  #if we are on the same filesystem
  my @path = split("/",$file);
  pop(@path);
  if(my @d = lstat(join("/",@path))){
    if(my @s = lstat($bestfilesofar)){
      if($d[0] == $s[0]){
        print "hardlink OK!\n" if $DEBUG;
        exit 0 unless runcmd("/bin/ln","-vf","$bestfilesofar","$file");
      }
    }
  }
  print "regular copy\n" if $DEBUG;
  exit runcmd("/bin/cp","-avf","$bestfilesofar","$file");
}


sub runcmd {
  print "DEBUG: ".join(" ", @_)."\n" if $DEBUG;
  return system(@_);
}
