#!/usr/bin/env perl

use strict;
use CGI;
use Data::Dumper;
use DBI;
my $cgi = new CGI;
print $cgi->header('text/html');
my %var = $cgi->Vars;
exit unless( $var{hostname} );
exit unless( $var{pubkey} );
chomp $var{hostname};
chomp $var{pubkey};
use YAML qw( LoadFile );

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 $query = "INSERT INTO pubkeys (serverid,pubkey) VALUES((SELECT serverid FROM server WHERE hostname=?), ?)";
my $sth = $dbh->prepare($query);
$sth->bind_param(1,$var{hostname}, { TYPE => &DBI::SQL_VARCHAR });
$sth->bind_param(2,$var{pubkey}, { TYPE => &DBI::SQL_LONGVARBINARY });
$sth->execute;
if ($sth->errstr =~ m/duplicate/i) {
    print "Entry already exists for $var{hostname}\n";
} elsif ($sth->errstr) {
    print "Error occured: $sth->errstr\n";
} else {
    print "Pubkey inserted for $var{hostname}\n";
}
