#!/usr/bin/perl
# Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.

# This script is entry point for backup content on remote service node

$ENV{'PATH'} = "/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin";

my $includeDir;
my $productRoot;
my $agentSessionPath;
my $base64;

BEGIN {
my %config;

my $configFileName = "/etc/psa/psa.conf";

open CONFIG, $configFileName;
binmode(CONFIG);
while (<CONFIG>) {
  chomp;
  next if /^#/;
  next if /^$/;
  if (/^\s*(\S+)\s+(\S+)\s*$/) {
    $config->{$1} = $2;
  }
}
close CONFIG;
$productRoot = $config->{'PRODUCT_ROOT_D'};
$includeDir = $config->{'PRODUCT_ROOT_D'} . "/PMM/agents/shared";
}

use lib $includeDir; 
use Storage::Storage;
use strict;
use Getopt::Long;

sub usage {
  my ($exitcode) = @_;
  
  my $usage = <<'EOF';  
EOF
  
  if ($exitcode) {
    print STDERR $usage;
  } else {
    print $usage;
  }

  exit $exitcode;  
}

sub backupContent {
  my (%settings) = @_;
  
  use Data::Dumper;
  
  $Data::Dumper::Varname = 'storage';
  
  my $filename = $settings{'args-file'};
  
  my (%options, $proposedId, $do_gzip, $workDir, $splitSize, $space_reserved, $sessionId, $passwd, $passiveMode);

  my $optionsString;
  my $storage;

  $optionsString = getFileContent($filename); 
  eval $optionsString;
  
  $ENV{'FTP_PASSWORD'} = $passwd;

  $storage = Storage::Storage::createFileStorage( $do_gzip, $workDir, $splitSize , undef, $space_reserved, $passiveMode);
      
  my $id = $storage->addTar($proposedId, %options);

  my $createdContentInfo = $agentSessionPath . "/" . $base64->{'ENCODE'}->($proposedId);
  open DATADUMPER, ">$createdContentInfo";
  print DATADUMPER Data::Dumper::Dumper($storage);
  close DATADUMPER;

  Logging::info("Created archive " . $id);
}

sub getFileContent {
  my ($filepath) = @_;
  
  if ( -e $filepath) {
    open FILEHANDLER, $filepath; 
    my $fileContent;
    binmode FILEHANDLER;
    while(<FILEHANDLER>) {
      chomp;
      $fileContent .= $_;
    }
    close FILEHANDLER;
    return $fileContent;
  } else {
    Logging::error("File " . $filepath . " does not exists");
  }
}

sub parseOptions {
  
  usage(0) unless @ARGV;
  usage(0) if $ARGV[0] eq "--help";

  my %res;
  
  my $command = '';  
  my $optParser = Getopt::Long::Parser->new(config => ['bundling']);
  
  $command = shift @ARGV;

  if (!$command) {
    die "No command in command line" unless (@ARGV);
  }

  usage(0) if $command eq "help";  
  
  my ($argsFile, $sessionId);
  
  $optParser->getoptions("args-file=s" => \$argsFile);
  $res{$command} = 1 ;
  
  $res{'args-file'} = $argsFile;  
  
  return %res;
}

sub getCreatedContentInfo {
  my (%settings) = @_;
  
  my $filename = $settings{'args-file'};
  
  my (%options, $proposedId, $do_gzip, $workDir, $splitSize, $space_reserved, $sessionId, $passwd, $passiveMode);

  my $optionsString = getFileContent($filename);
  eval $optionsString;
  my $createdContentInfo = $agentSessionPath . "/" . $base64->{'ENCODE'}->($proposedId);
  getFileContent($createdContentInfo); 
}

sub main {
  my %settings = parseOptions();

  $base64 = HelpFuncs::makeMIMEBase64();

  my (%options, $proposedId, $do_gzip, $workDir, $splitSize, $space_reserved, $sessionId, $passwd, $passiveMode);
  
  my $optionString = getFileContent($settings{'args-file'});
  eval $optionString;
  
  my $logfileHandle;
  my $sessionPath;
  if( defined $sessionId ) {
    
    $sessionPath = $productRoot . "/PMM/sessions/" . $sessionId;
    
    if (defined $settings{'destroy-session'}) {
      HelpFuncs::deleteFolder($sessionPath);
    } else {
      if ( not -e $sessionPath ) {
        system("mkdir", "-p", "$sessionPath");
      }

      $agentSessionPath = $sessionPath;

      open $logfileHandle, ">> $sessionPath/psadump.log";
      Logging::setOutput( $logfileHandle );
      Logging::setXmlLogging();
    }
  }
  
  if (exists $settings{'backup-content'}) {
    backupContent(%settings);
  }
  
  if (exists $settings{'get-created-content-info'}) {
    print STDOUT getCreatedContentInfo(%settings);
  }

  if (exists $settings{'get-logs'}) {
    print STDOUT getFileContent("$sessionPath/psadump.log");
  }
  
  if( defined $sessionId and not defined $settings{'destroy-session'} ){  
    close Logging::getOutput();
  }
  
  return 0;
}

my $exitcode = main();
exit($exitcode);

