#!/usr/bin/perl
use strict;
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;
#$Data::Dumper::Indent = 0;
use File::Slurp;
use File::Path qw(make_path);
use FindBin qw($Bin);
use lib "$Bin/../lib";
use BackupServer;
use Proc::Daemon;
use Proc::PID::File;

my $args = {@ARGV};
my $time = time();
my $stats = {
    gsutils_bytes => 0,
    success => 0,
    fail => 0,
    attempts => 0,
  };

# create backupserver object
my $bs_args = {};
$bs_args->{debug_stdout} = 1 if ! defined($args->{background});
my $bk = BackupServer->new($bs_args);

# some default config entries
my $conf = {
  state_dir => '/opt/eig_linux/data/obj-backups/',
};
foreach my $k (keys %$conf){
  my $val = $bk->get_config_value("obj_${k}");
  # if we have a config entry, use that instead
  if(defined($val)){
    $conf->{$k} = $val;
  }
}

my $dr_servers = $bk->get_gcp_dr_clients();

if(defined($args->{background})){
  # disconnect from calling process
  Proc::Daemon::Init();
}

# must do after you daemonize
# ensure no other instance is running
if(Proc::PID::File->running()){
  $bk->logger('LOG_WARNING',"Already running!");
  exit 1;
}
##
## iterate through dr_servers
##
foreach my $host (keys %$dr_servers){
  # let's make sure the events directories exists
  my @dirents = read_dir("/home/$host/");
  foreach my $ent(@dirents){
    if($ent =~ m/^backup[0-9]?$/){
      my $eventdir = "/home/$host/$ent/events";
      if (! -e $eventdir){
        make_path($eventdir, {mode => 0700});
      }
    }
  }

  # if we don't have state there isn't anything for us to do here
  if(! -d "$conf->{state_dir}/$host"){
    $bk->logger('LOG_WARNING',"$conf->{state_dir}/$host does not exist");
    next;
  }

  # server is not yet fully configured if it doesn't have a bucket_name
  next if ! defined($dr_servers->{$host}->{bucket_name});

  my $uri = lc(sprintf("gs://%s/state/obj-state.%d.tar.bz2",$dr_servers->{$host}->{bucket_name},$time));

  #print "$uri\n";
  my $gsutils_log_file = "/tmp/obj-state-$host.$time.log";
  my $gsutils_args = "-L $gsutils_log_file";
  # bucket is configured as STANDARD storage and will delete after 7 days if STANDARD object
  my $cmd = "/usr/bin/tar --create --sparse --xattrs -C $conf->{state_dir} $host |/usr/bin/bzip2 |/usr/bin/gsutil cp $gsutils_args - $uri";
  $stats->{attempts}++;
  $bk->logger('LOG_WARNING',"tarball command: $cmd");
  system($cmd) if ! defined($args->{skip_tar});

  # check status
  my $response = check_gsutil_status($gsutils_log_file,$uri);
  if($response ne 'OK'){
    $bk->logger('LOG_WARNING', "failure $uri $response");
    $bk->logger('LOG_WARNING',Dumper($args));
    $bk->logger('LOG_WARNING',"review $gsutils_log_file for more details");
    $stats->{fail}++;
  }else{
    $bk->logger('LOG_NOTICE', "state file $uri uploaded for $host");
    unlink($gsutils_log_file);
    $stats->{success}++;
  }
}
my $endtime = time();
my $duration = $endtime - $time;
if($stats->{gsutils_bytes} > 0 and $duration > 0){
  $stats->{gsutils_bytes_per_sec} = sprintf("%.2f", $stats->{gsutils_bytes} / $duration );
}
$bk->logger('LOG_NOTICE',"done syncing state $time bytes: $stats->{gsutils_bytes} bps: $stats->{gsutils_bytes_per_sec}");

sub check_gsutil_status {
  my $log_file = shift;
  my $uri = shift;
  if(defined($args->{skip_tar})){
    return "SKIP_TAR_IS_SET";
  }
  my @logfile = read_file("$log_file");
  foreach my $ol (@logfile){
    next if $ol !~ m/$uri/;
    $ol =~ s/[\n\r]$//;
    #chomp($ol);
    my @attrib = split(',',$ol);
    $bk->logger('LOG_NOTICE', "gsutil status on file is: ".join(" ",@attrib));
    if($attrib[7] =~ m/^[0-9]+$/){
      $stats->{gsutils_bytes} += $attrib[7];
    }
    return($attrib[8]);
  }
}
