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

my $hal_id = $var{'hal_id'};
my $hal_instance_id = $var{'hal_instance_id'};
my $status = $var{'status'};
my $reason = $var{'reason'};
my $data = {};

#statuses:
#STARTED
#RUNNING
#COMPLETE
#FAILED

my $config = LoadFile("/var/www/conf/vpsbackup_master_config.yaml") || die "Failed to load config: $!\n";

my $dbh = DBI->connect("DBI:mysql:database=".$config->{vps_backup_db}.";host=localhost",$config->{vps_backup_user}, $config->{vps_backup_pass}) or die("couldnt connect to db $!");

my $query = "";

if ($status =~ /STARTED/){
    $query = "update volume set status = ?, status_time = NOW(), backup_start_time = NOW(), backup_end_time = NULL where hal_id = ? and hal_instance_id = ? limit 1 ";
} elsif ($status =~ /COMPLETE/){
    $query = "update volume set failure_count = 0, status = ?, status_time = NOW(), backup_end_time = NOW() where hal_id = ? and hal_instance_id = ? limit 1 ";
} elsif ($status =~ /FAILED/){
    $query = "update volume set failure_count = failure_count + 1, status = ?, status_time = NOW(), last_failure_time = NOW(), backup_end_time = NOW(), last_failure_reason = ? where hal_id = ? AND hal_instance_id = ? limit 1 ";
} else {
    $query = "update volume set status = ?, status_time = NOW() where hal_id = ? and hal_instance_id = ? limit 1 ";
}


my $sth = $dbh->prepare($query) or die("Error:".$dbh->errstr."\n");
if ( $status ne 'FAILED' ) {
    $sth->execute($status, $hal_id, $hal_instance_id) || die("Error:".$sth->errstr."\n");
} else {
    $sth->execute($status, $reason, $hal_id, $hal_instance_id) || die("Error:".$sth->errstr."\n");
}
$sth->finish;
