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


my $remote_ip = $ENV{REMOTE_ADDR};
if( $ENV{REMOTE_ADDR} eq '127.0.0.1' || $ENV{REMOTE_ADDR} eq '74.220.198.194' || -t STDOUT ) {
  $remote_ip = $var{ip} if defined ($var{ip});
}

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

my $data = {};

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 = "select id,hostname,inet_ntoa(publicip) as publicip ,inet_ntoa(privateip) as privateip, type, publickey from backup where publicip = inet_aton(?) or privateip = inet_aton(?);";
my $gwh = $dbh->prepare($query) or die("Error:".$dbh->errstr."\n");

$gwh->execute($remote_ip,$remote_ip) || die("Error:".$gwh->errstr."\n");
$data->{self} = $gwh->fetchrow_hashref();

$gwh->finish;
if( ! defined($data->{self}->{id})){
#  print "I have no data for you\n";
  print Dump({data => 'There is none'});
  exit;
}

if($data->{self}->{type} ne 'block'){
  my $bmh = $dbh->prepare(" SELECT    bm.gateway_port AS gateway_port,
          g.hostname AS gatewayhostname,
          inet_ntoa(g.publicip) AS gatewaypublicip,
          v.hostname AS vpshostname,
          v.size AS vpssize,
          v.type AS vpstype
          FROM backupmap bm
          LEFT JOIN gateway g ON bm.gateway_id = g.id
          LEFT JOIN vps v ON bm.vps_id = v.id
          WHERE bm.backup_id = ?");

  $bmh->execute($data->{self}->{id}) || die("Error:".$bmh->errstr."\n");
  while( my $ref = $bmh->fetchrow_hashref()){
    push(@{$data->{backupmap}},$ref);
  }
  $bmh->finish;
}else{
  # similar query as above, but with instances
  my $bmh = $dbh->prepare('SELECT
              bm.gateway_port AS gateway_port,
              g.hostname AS gatewayhostname,
              inet_ntoa(g.publicip) AS gatewaypublicip,
              v.hostname AS vpshostname,
              inet_ntoa(v.privateip) AS vpsprivateip,
              i.id as instance_id,
              i.uuid AS instanceuuid,
              i.brand AS  instancebrand,
              inet_ntoa(i.primary_ip) AS primaryip,
              i.hal_status AS status
              FROM backupmap bm
              LEFT JOIN gateway g ON bm.gateway_id = g.id
              LEFT JOIN vps v ON bm.vps_id = v.id
              LEFT JOIN instance i ON v.id = i.vps_id
              WHERE bm.backup_id = ?
                          AND i.last_hal_push >= now() - INTERVAL 1 DAY;');
  # look for volumes attached to a given vm
  my $vh = $dbh->prepare('SELECT        v.disk_size AS disk_size,
              v.hal_id AS hal_vol_id,
              v.hal_instance_id AS hal_server_id,
              s.hostname AS sanhostname,
              s.id + 3000 AS gateway_port,
              inet_ntoa(s.ip) AS sanprivateip
                          FROM volume v
                          LEFT JOIN san s on v.san_id = s.id
                          WHERE v.instance_id = ?
                          AND v.last_hal_push >= now() - INTERVAL 1 DAY;');

  $bmh->execute($data->{self}->{id}) || die("Error:".$bmh->errstr."\n");
  while( my $ref = $bmh->fetchrow_hashref()){
     $vh->execute($ref->{instance_id}) || die("Error: ".$vh->errstr."\n");
     while( my $vref = $vh->fetchrow_hashref()){
       push(@{$ref->{volumes}},$vref);
     }
     $vh->finish;
    push(@{$data->{instances}},$ref);
  }
  $bmh->finish;
}

print Dump($data);



