#!/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 from gateway where publicip = inet_aton(?) or privateip = inet_aton(?);";
my $gwh = $dbh->prepare($query);

$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;
}


#legacy san
if($data->{self}->{id} eq 2){
  my $bmh = $dbh->prepare("SELECT hostname as backuphostname,inet_ntoa(publicip) as backuppublicip FROM backup WHERE type = 'block'");
  $bmh->execute() || die("Error:".$bmh->errstr."\n");
  while( my $ref = $bmh->fetchrow_hashref()){
    push(@{$data->{backup}},$ref);
  }
  $bmh->finish;
  my $bmh = $dbh->prepare("SELECT hostname ,id+2000 as gateway_port,inet_ntoa(privateip) as ip FROM vps WHERE type = 'block'");
  $bmh->execute() || die("Error:".$bmh->errstr."\n");
  while( my $ref = $bmh->fetchrow_hashref()){
    push(@{$data->{dat}},$ref);
  }
  $bmh->finish;
  my $bmh = $dbh->prepare("SELECT hostname ,id+3000 as gateway_port,inet_ntoa(ip) as ip FROM san");
  $bmh->execute() || die("Error:".$bmh->errstr."\n");
  while( my $ref = $bmh->fetchrow_hashref()){
    push(@{$data->{dat}},$ref);
  }
  $bmh->finish;
  print Dump($data);

}else{
  #new stuff
  my $bmh = $dbh->prepare("SELECT    b.hostname AS backuphostname,
          inet_ntoa(b.publicip) AS backuppublicip
          FROM backupmap bm
          LEFT JOIN backup b ON bm.backup_id = b.id
          WHERE gateway_id = ?");
  $bmh->execute($data->{self}->{id}) || die("Error:".$bmh->errstr."\n");
  while( my $ref = $bmh->fetchrow_hashref()){
    push(@{$data->{backup}},$ref);
  }
  $bmh->finish;
  my $bmh = $dbh->prepare("SELECT    v.hostname AS hostname,
          bm.gateway_port AS gateway_port,
          inet_ntoa(v.privateip) AS ip
          FROM backupmap bm
          LEFT JOIN vps v ON bm.vps_id = v.id
          WHERE gateway_id = ?");
  $bmh->execute($data->{self}->{id}) || die("Error:".$bmh->errstr."\n");
  while( my $ref = $bmh->fetchrow_hashref()){
    push(@{$data->{dat}},$ref);
  }
  $bmh->finish;

  print Dump($data);

}

