#!/usr/bin/perl
use strict;
use CGI;
use Data::Dumper;
use DBI;
my $cgi = new CGI;
print $cgi->header('text/html');
my %var = $cgi->Vars;
use YAML 'LoadFile';
my $config_settings = LoadFile("/var/www/conf/backup_master_config.yaml") || die "Failed to load config: $!\n";

my $validated = 0;
foreach my $regex ( @{ $config_settings->{"valid_ips"} } ) {
        $validated = 1 if ( $ENV{REMOTE_ADDR} =~ m/^$regex/ );
}
exit if ( !$validated );


exit unless($ENV{REMOTE_ADDR} eq "74.220.195.6" or $ENV{REMOTE_ADDR} eq "69.89.16.119" or $ENV{REMOTE_ADDR} eq "72.8.80.75" or $ENV{REMOTE_ADDR} eq "74.220.198.34" or $ENV{REMOTE_ADDR} =~ /74\.220\.196/);

my $dbh = DBI->connect("DBI:mysql:database=".$config_settings->{backup_db}.";host=localhost",$config_settings->{backup_user}, $config_settings->{backup_pass}) or die("couldnt connect to db $!"); 

my @columns = qw{ hostname version field oldvalue newvalue timestamp };
my %columnformat;
$columnformat{hostname} = "%26s";
$columnformat{version} = "%26s";
$columnformat{field} = "%26s";
$columnformat{oldvalue} = "%5s";
$columnformat{newvalue} = "%5s";
$columnformat{timestamp} = "%26s";

my %backupbox;
my $colortogle = 1;

bboxmap(\%backupbox);
if(defined($var{box})){
  boxhistory(\%var,\@columns)
}else{
  mountpointproblems(\%backupbox,\@columns);
}

sub boxhistory {
  my $var_ref = shift;
  my $columns_ref = shift;
  my $query = sprintf('select * from backupstatechanges where hostname = %s order by timestamp desc limit 100', $dbh->quote($$var_ref{box}));
  my $sth = $dbh->prepare($query) or warn $dbh->errstr;
  $sth->execute();# or warn $sth->errstr;
  print starttable();
  my $curday = "Mon";
  my @response;

  while(my $ref = $sth->fetchrow_hashref()){
    my $oneline = "";
    next if $ref->{field} =~ m/lastrun-date/;
    next if $ref->{field} =~ m/cpanel-accounts-total/;
    my $day = substr(localtime($ref->{timestamp}),0,3);
    if($curday ne $day){
      $colortogle++;
      $colortogle = $colortogle % 2;
      $curday = $day;
    }
    $oneline .= startrow();
    foreach my $key (@$columns_ref){
      my $value = $ref->{$key};
      if($key eq "timestamp"){
        $value = localtime($value);
      }
      $oneline .= returnvalue($value);
    }
    $oneline .= endrow();
    unshift(@response, $oneline);
  }
  foreach(@response){;
    print $_;
  }
  print endtable();
}
sub starttable {
  return "<table>\n";
}
sub endtable {
  return "</table>\n";
}
sub startrow {
  if($colortogle){
    return "<tr>";
  }else{
    return "<tr bgcolor=#5CB3FF>";
  }
}
sub endrow {
  return "</tr>\n";
}
sub returnvalue {
#  if($colortogle){
#    print "<td bgcolor='#5CB3FF'>@_</td>";
#  }else{
   return "<td>@_</td>";
#  }
}

sub bboxmap{
  my $backupbox_ref = shift;;
  my $query = "SELECT DISTINCT chostname,bhostname FROM iscsiview";
  my $sth = $dbh->prepare($query);
  $sth->execute or warn $sth->errstr;

  while(my $ref = $sth->fetchrow_hashref()){
    my $value = $ref->{bhostname};
    $value =~ s/\.bluehost\.com/.BH/g;
    $value =~ s/\.hostmonster\.com/.HM/g;
    $value =~ s/\.fastdomain\.com/.FD/g;
    if(defined($$backupbox_ref{$ref->{chostname}})){
      $$backupbox_ref{$ref->{chostname}} .= " ".$value;
    }else{
      $$backupbox_ref{$ref->{chostname}} = $value;
    }
  }
  $sth->finish;
}


sub mountpointproblems{
  my $backupbox_ref = shift;
  my $columns_ref = shift;
  my $query = "select ".join(',', map($dbh->quote_identifier($_), @$columns_ref))." from backupstatechanges where field = 'mountpoint-problems' and newvalue != 0 ";
  my $sth = $dbh->prepare($query) or warn $dbh->errstr;
  $sth->execute or warn $sth->errstr;

  unshift @$columns_ref, "bbox";

  while(my $ref = $sth->fetchrow_hashref()){
    foreach my $key (@$columns_ref){
      if($key eq "bbox"){
        if(defined($$backupbox_ref{$ref->{hostname}})){
          printf("%26s", $$backupbox_ref{$ref->{hostname}});
        }else{
          printf("%26s", "unknown");
        }
        next;
      }
      my $value = $ref->{$key};
      if($key eq "timestamp"){
        $value = localtime($ref->{$key});
      }
      if(defined($columnformat{$key})){
        printf($columnformat{$key},$value);
      }else{
        printf("%26s", $value);
      }
  #    if(defined($data->{$ref->{hostname}}->{$key})){
  #      $data->{$ref->{hostname}}->{$key} .= "<br>\n".$ref->{$key};
  #    }else{
  #      $data->{$ref->{hostname}}->{$key} = $ref->{$key};
  #    }
    }
    print "\n";
  }
  $sth->finish;
  
}
#print Dumper($data);

