#!/usr/bin/perl

use strict;
#use Data::Dumper;
my $DEBUG = 0;
use Proc::Daemon;
Proc::Daemon::Init unless $DEBUG;

use Proc::PID::File;

if (Proc::PID::File->running()){
  print "appears another instance of $0 is running\n";
  exit();
}

my $mysqldir = "/var/lib/mysql";
my $checkdir = "/usr/sec/data/mysql";
my $checklog = "/usr/sec/data/mysqlcheck.out";
rename("$checklog.2", "$checklog.3") if(-e  "$checklog.3");
rename("$checklog.1", "$checklog.2") if(-e  "$checklog.1");
rename("$checklog",   "$checklog.1") if(-e  "$checklog"  );

close(STDERR);
close(STDOUT);
open(STDOUT, ">>$checklog");
open(STDERR, ">>$checklog");

print localtime(time)."\n";

if( -e "/etc/chkmysqldb"){
  system("time /usr/sec/bin/chkmysqldb");
  system("time /usr/sec/bin/chkmysqldb --fix");
  exit;
}

mkdir($checkdir, 0700) unless -d $checkdir;

opendir(MYSQL, $mysqldir);
my @mysqldirs = readdir(MYSQL);
close(MYSQL);

my $data = {};
my $totals = {};
foreach my $db (sort @mysqldirs){
  next if $db =~ m/^\./;
  next if $db eq "lost+found";
  next if $db eq "GRAVEYARD";
  next unless -d "$mysqldir/$db";
  lastupdated(\$data, $db, \$totals);
  mkdir("$checkdir/$db", 0700) unless -d "$checkdir/$db";
  $totals->{"databases-total"}++;
  foreach my $table (sort keys %{$data->{$db}}){
    $data->{$db}->{$table}->{type} = 'other' unless defined($data->{$db}->{$table}->{type});
    $totals->{"tables-total"}++;
    $totals->{"tables-type-".$data->{$db}->{$table}->{type}}++;
    my $needwork = 1;
    $needwork = 0 if $data->{$db}->{$table}->{type} eq "other";
    $needwork = 0 if $data->{$db}->{$table}->{type} eq "InnoDB";
    if(my @stat = stat("$checkdir/$db/$table")){
      $needwork = 0 if($data->{$db}->{$table}->{updated} < $stat[9]);
    }
    unless($table =~ m/^[a-z0-9\-\_\@\.]+$/i){
      $totals->{"tables-name-skipped"}++;
      next;
    }
    if($needwork){
      #do work on the database
      workon($db, $table);
      $totals->{"space-type-".$data->{$db}->{$table}->{type}."-modif"} += $data->{$db}->{$table}->{size};
      #touch the applicable file
      my $now = time + 60;
#      utime($now, $now, "$checkdir/$db/$table");
      open(FILE, ">", join("/", ($checkdir,$db,$table)));
      close(FILE);
      utime($now, $now, "$checkdir/$db/$table");
      $totals->{"tables-modif"}++;
    }else{
      $totals->{"tables-skipped"}++;
    }
  }
  sleep 5;
}
#clean up old datafiles
opendir(CHECK, $checkdir);
my @checkdirs = readdir(CHECK);
close(CHECK);
foreach my $db (@checkdirs){
  next if $db =~ m/^\./;
  next if $db eq "lost+found";
  next if $db eq "GRAVEYARD";
  next unless -d "$mysqldir/$db";
  unless(defined($data->{$db})){
    print "directory $mysqldir/$db shouldn't be there\n";
  }else{
    opendir(DIR, "$mysqldir/$db");
    my %tables = {};
    while(<DIR>){
      $tables{$_} = 1;
    }
    close(DIR);
    #clean up old tables!
    opendir(DIR, "$checkdir/$db");
    while(<DIR>){
      print "$_ shouldn't exist" unless defined $tables{$_};
    }
    close(DIR);
  }
}

#print Dumper($data);
#print Dumper($totals);

print "\nTOTALS:\n";
foreach my $ent (sort keys %$totals){
  printf("%-25s %10d\n", $ent, $totals->{$ent});
}

print "\n".localtime(time)."\n\n";

#
#subs only below this line
#
sub workon {
  my $db = shift;
  my $table = shift;
  my @command = qq{ mysqlcheck -r --use-frm $db $table ; mysqlcheck -a $db $table ; mysqlcheck -o $db $table };
  print "DEBUG: ".join(" ",@command)."\n" if $DEBUG;
  return system(@command);
}

sub lastupdated {
  my $data_ref = shift;
  my $db = shift;
  my $totals_ref = shift;
  opendir(DIR, "$mysqldir/$db");
  my @entries = readdir(DIR);
  close(DIR);
  foreach my $file (@entries){
    next if $file =~ m/^\./;
    next if $file eq "db.opt";
    my $extension = substr($file,(length($file) - 3), 3);
    my $tablename = substr($file,0,(length($file) - 4));
    my @stats = stat("$mysqldir/$db/$file");
    $$data_ref->{$db}->{$tablename}->{size} += $stats[7];
    if($$data_ref->{$db}->{$tablename}->{updated}){
      $$data_ref->{$db}->{$tablename}->{updated} = $stats[9] if($stats[9] > $$data_ref->{$db}->{$tablename}->{updated});
    }else{
      $$data_ref->{$db}->{$tablename}->{updated} = $stats[9];
    }
    if($extension eq "MYI"){
      $$data_ref->{$db}->{$tablename}->{type} = "MyISAM";
      $$totals_ref->{"space-MyISAM"} += $stats[7];
    }elsif($extension eq "MYD"){
      $$data_ref->{$db}->{$tablename}->{type} = "MyISAM";
      $$totals_ref->{"space-MyISAM"} += $stats[7];
    }elsif($extension eq "ibd"){
      $$data_ref->{$db}->{$tablename}->{type} = "InnoDB";
      $$totals_ref->{"space-InnoDB"} += $stats[7];
    }elsif($extension eq "CSV"){
      $$data_ref->{$db}->{$tablename}->{type} = "CSV";
      $$totals_ref->{"space-CSV"} += $stats[7];
    }elsif($extension eq "CSM"){
      $$data_ref->{$db}->{$tablename}->{type} = "CSV";
      $$totals_ref->{"space-CSV"} += $stats[7];
    }elsif($extension eq "ARZ"){
      $$data_ref->{$db}->{$tablename}->{type} = "ARCHIVE";
      $$totals_ref->{"space-ARCHIVE"} += $stats[7];
    }elsif($extension eq "frm"){
      $$totals_ref->{"space-frm"} += $stats[7];
    }else{
      $$data_ref->{$db}->{$tablename}->{type} = "other" unless defined($$data_ref->{$db}->{$tablename}->{type});
      $$totals_ref->{"space-OTHER"} += $stats[7];
    }
    $$totals_ref->{"space-total"} += $stats[7];
  }
}



