#!/usr/bin/perl
use strict;
use DBI;
use CGI;
use YAML qw(Dump LoadFile);
use Data::Dumper;
my $cgi = new CGI;
print $cgi->header();
my %var = $cgi->Vars;

exit unless(defined($var{hostname}));
# we should validate the hostname matches the IP and bail out if not

my $config_settings = LoadFile("/var/www/conf/backup_master_config.yaml") || die "Failed to load config: $!\n";
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 $mounts = getcurrentmounts($var{hostname});
getmigrationservers($var{hostname},$mounts);
correctpartitionsize($mounts);

# Make sure all entries have homesize;
foreach my $entry( keys %$mounts){
    $mounts->{$entry}->{need} //= $mounts->{$entry}->{homesize};
}

print Dump $mounts;

# Calculates the need variable and sets the homesize based on backupstate date, if available
sub correctpartitionsize {
    my $mounts = shift;
    foreach my $ent (sort keys %{$mounts}){
        my $num = 0;
        next unless ($mounts->{$ent}->{cmount} =~ m/backup(\d+)/); 
        $num = $1;
        my $query = "SELECT homesize,homeused,backupused FROM backupstatepartitions WHERE hostname = ? and pnum = ?";
        my $sth = $dbh->prepare($query);
        $sth->bind_param(1,$mounts->{$ent}->{chostname}, {TYPE => &DBI::SQL_VARCHAR}) or warn $sth->errstr;
        $sth->bind_param(2,$num,{ TYPE => &DBI::SQL_INTEGER }) or warn $sth->errstr;
        $sth->execute or warn $sth->errstr;
        while (my $ref = $sth->fetchrow_hashref()) {
            my $size = $ref->{homeused} * 1.5;
            $size = 480000000 if (480000000 > $size);
            $size = 550000000 if (550000000 > $size and $ref->{homesize} >  700000000);
            $size = 660000000 if (660000000 > $size and $ref->{homesize} > 1400000000);
            $size = 750000000 if (750000000 > $size and $ref->{homesize} > 1800000000);
            if(($ref->{backupused} * 1.1) > $size){
                $size = $ref->{backupused} * 1.25;
            }
            if(($ref->{homesize} * 1.5) < $size){
                $size = $ref->{homesize} * 1.5;
            }
            $mounts->{$ent}->{homesize} = sprintf("%.2f",  $ref->{homesize} / (1024 * 1024 * 1024));
            $mounts->{$ent}->{need} = sprintf("%.2f",  $size / (1024 * 1024 * 1024));
        }
    }
}

# Gets the current mounts for a given server
sub getcurrentmounts {
    my $hostname = shift;
    my $mounts;
    my $query = q(
            SELECT pubkeys.pubkey,chostname,server.serverid,
            INET_NTOA(newbacknetip.backnetip) as backnetip,
            cmount,bhostname,plabel,homesize FROM iscsiview 
            LEFT JOIN `server` on iscsiview.chostname = server.hostname 
            LEFT JOIN `pubkeys` on server.serverid = pubkeys.serverid 
            LEFT JOIN `newbacknetip` on server.serverid = newbacknetip.serverid 
            WHERE chostname = ? or bhostname = ? 
            ORDER BY plabel
            );
    my $sth = $dbh->prepare($query);
    $sth->execute($hostname, $hostname) or warn $sth->errstr;
    my $count = 0;
    while(my $ref = $sth->fetchrow_hashref()){
        $count++;
        foreach(keys %$ref){
            $mounts->{$count}->{$_} = $ref->{$_};
        }
    }
    $sth->finish;
    return $mounts;
}

# Adds in any servers being migrated to the data
sub getmigrationservers {
    my $hostname = shift;
    my $mounts = shift;
    my $query = q(
            SELECT cbox.hostname AS chostname,pubkeys.pubkey,dest.hostname as bhostname,
            iscsiview.plabel as plabel,iscsiview.homesize as homesize,iscsiview.cmount as cmount,
            source.serverid,INET_NTOA(newbacknetip.backnetip) AS backnetip FROM backupmigrations
            LEFT JOIN `server` AS source ON source.serverid = sourceid
            LEFT JOIN `server` AS dest ON dest.serverid = destid
            LEFT JOIN `server` AS cbox ON cbox.serverid = cboxid
            LEFT JOIN `pubkeys` on pubkeys.serverid = sourceid
            LEFT JOIN `newbacknetip` on sourceid = newbacknetip.serverid
            LEFT JOIN `iscsiview` on cbox.hostname = iscsiview.chostname
            WHERE dest.hostname = ?
            AND backupmigrations.status in ('queued','running','failed')
            ORDER BY iscsiview.plabel
            );
    my $sth = $dbh->prepare($query);
    $sth->execute($hostname) or warn $sth->errstr;
    my $res = $sth->fetchall_hashref('plabel');
    my $index = (keys %$mounts) + 1;
    foreach my $mig_server (keys %$res){
        $mounts->{$index} = $res->{$mig_server};
        $index++;
    }
    return $mounts;
}
