#!/usr/bin/env perl
use strict;
use Data::Dumper;
use FindBin;
use File::Temp qw( tempfile );
use File::Slurp qw( read_file );
use CGI;
use lib "/opt/eig_linux/lib";
use lib "$FindBin::Bin/../lib";

use BackupMaster::CGI;
use BackupMaster::Server;

my $args = {@ARGV};
my $cgi = BackupMaster::CGI->new($args);


#use BackupMaster::BackupMaster;

# to validate that the request comes from a valid gateway (and therefore trusted)
#use BackupMaster::Server;

# do we have a service account by that name already?
use BackupMaster::GCP_Backuping_Service_Account;

if(! -e '/bin/gcloud'){
  $cgi->error_out("no gcloud installed");
}

# remember remote_ip can be passed as an argument when local or connecting from a trusted_ip
my $s_obj = BackupMaster::Server->new();
my $list = $s_obj->do('list',{ ip => $cgi->remote_ip() , select => 'hostname,ip'});
if( ref($list) ne 'ARRAY' or @$list == 0){
    $cgi->error_out( "your kind is not welcome here, you have to wait outside");
}
$args->{hostname} = @$list[0]->{hostname};


my $bsa = new BackupMaster::GCP_Backuping_Service_Account({hostname => $args->{hostname}});
if( ! defined($bsa->{info})){
  $cgi->error_out("BSA not found for hostname");
}

if( defined($bsa->{info}->{key_downloaded}) and $bsa->{info}->{key_downloaded} ){
  $cgi->error_out("key has already been downloaded for $args->{hostname}");
}

if( ! defined $bsa->{info}->{service_account_email}){
  $cgi->error_out("service account not created yet");
}

# made it past all checks... let's download the key
my $filename = "/tmp/tmpkey.$$.$args->{hostname}.json";

my $cmd = sprintf("gcloud iam service-accounts keys create %s --iam-account=%s 2>/dev/null >/dev/null",$filename,$bsa->{info}->{service_account_email});
#$cgi->print("cmd: $cmd\n");
$bsa->update({id => $bsa->{info}->{id}, key_downloaded => 1});
system($cmd);
if(! -s $filename){
  $bsa->update({id => $bsa->{info}->{id}, key_downloaded => 0});
  $cgi->error_out("command failed to create keyfile");
  exit;
}

my $contents = read_file($filename);
$cgi->content_type('application/json');
$cgi->print("$contents\n");
unlink $filename if -e $filename;

