#!/usr/bin/perl
use strict;
use DBI;

my $DEBUG = 0;
my $MYSQLDIR = "/var/lib/mysql";
my $mustdump = 0;
my $dblastupdated = 0;
my @safetouseolddumps = qw{ MYD frm MYI opt CSV };
my $bestfilesofar = "";
my $eig_backup_config_file = '/opt/eig_linux/etc/eig_backup.conf';
my $loglocation = '/var/log/eig_backup/mysqldumper.log';
my %eig_backup_config;
my $large_db = 0;
my $dump_large_dbs = is_weekend();

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
load_config();
opendir(DIR, "$MYSQLDIR/$db") or logger("Unable to find database folder, dumping...") and exit 1;
my @entries = readdir(DIR);
close(DIR);
check_crashed_tables();
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;
}
if (defined $eig_backup_config{'max_user_mysql_table_count'}){
  my $tablecount = getdbtablecount($db);
  if ($tablecount >= $eig_backup_config{'max_user_mysql_table_count'}){
    print "large database detected ($tablecount tables), we are skipping dump unless it is sat night backups!\n" if $DEBUG;
    $large_db = 1;
    $mustdump = 0 unless $dump_large_dbs;
  }
}
if (!$large_db && defined $eig_backup_config{'max_user_mysql_size'}){
  my $size = getdbsize($db);
  if ($size >= $eig_backup_config{'max_user_mysql_size'}){
    print "large database detected ($size bytes), we are skipping dump unless it is sat night backups!\n" if $DEBUG;
    $large_db = 1;
    $mustdump = 0 unless $dump_large_dbs;
  }
}
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 || ($large_db and !$dump_large_dbs) ){
          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];
          }
        }
      }
    }
  }
}

if ($bestfilesofar eq ""){
  logger("No backup found for large db, dumping...") if ($large_db && $dump_large_dbs);
  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");
}

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

sub load_config {
  open(DC, "<$eig_backup_config_file");
  foreach my $line (<DC>) {
    $eig_backup_config{$1} = $2 if ($line =~ m/^([^=]+?)=(.+)$/);
  }
  close(DC);
}

sub getdbsize {
  my $db = shift;
  my $dsn =
    "DBI:mysql:;" .
    "mysql_read_default_file=/root/.my.cnf";
  my $dbh = DBI->connect(
    $dsn,
    undef,
    undef,
    {RaiseError => 0}
  ) or return 0;
  my $query =q{SELECT SUM(data_length + index_length) 'SIZE' FROM information_schema.TABLES WHERE table_schema=?};
  return eval { ($dbh->selectrow_array($query, {}, $db))[0]; } || 0;
}

sub getdbtablecount {
  my $db = shift;
  my $dsn =
    "DBI:mysql:;" .
    "mysql_read_default_file=/root/.my.cnf";
  my $dbh = DBI->connect(
    $dsn,
    undef,
    undef,
    {RaiseError => 0}
  ) or return 0;
  my $query =q{SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND table_schema=?};
  return eval { ($dbh->selectrow_array($query, {}, $db))[0]; } || 0;
}

sub is_weekend {
  my $is_weekend = 0;
  my (undef,undef,$hour,undef,undef,undef,$wday) = localtime(time);
  $is_weekend = 1 if $wday == 6 and $hour >= 20;
  $is_weekend = 1 if $wday == 0 and $hour <= 6;
  return $is_weekend;
}

sub check_crashed_tables {
  my $dsn =
    "DBI:mysql:;" .
    "mysql_read_default_file=/root/.my.cnf";
  my $dbh = DBI->connect(
    $dsn,
    undef,
    undef,
    {RaiseError => 0}
  ) or return 0;
  my $query =q{SELECT * FROM information_schema.tables WHERE engine IS NULL AND table_comment LIKE '%is marked as crashed%' AND table_schema=?};
  my $res = $dbh->selectall_arrayref($query, {}, $db);
  foreach my $row (@$res){
    my $table = (@$row)[2];
    my $rawsize;
    foreach my $type qw( MYD MYI frm ){
       $rawsize += -s "/var/lib/mysql/$db/$table.$type" if (-f "/var/lib/mysql/$db/$table.$type"); 
    }
    my $size = sprintf "%.02f", ($rawsize/1024/1024);
	if ($size >= 2000){ #Skipping if we are over 2GB 
      logger("Skipping due to crashed table $table with size $size MB");
      exit 0;
    }else{
      logger("Found crashed table $table with size $size MB");
    }
  }
}

sub logger {
  my $message = shift;
  print "$message\n" if $DEBUG;
  my $entry = localtime(time()) .  ":$db: $message\n";
  open(LOG, ">>$loglocation");
  print LOG $entry;
  close(LOG);
}
