#!/bin/sh
#
# Untar a new set of config files for ZXTM

# Ensure ZEUSHOME is setup to point to our installation
if [ -z "$ZEUSHOME" ]
then
    # Have a good guess, we live in $ZEUSHOME/zxtm/bin
    OLD_PWD=`pwd`
    cd `dirname $0`/..
    cd ..
    ZEUSHOME=`pwd`
    export ZEUSHOME
    cd $OLD_PWD
fi

if [ ! -d "$ZEUSHOME/zxtm" ]
then
   echo "untar-config FATAL: ZEUSHOME not set"
   exit 1
fi

# Try to get networking commands into our PATH
PATH=/sbin:/usr/etc/sbin:/usr/etc:/usr/sbin:$PATH

# Restart ourselves in perl
exec $ZEUSHOME/perl/miniperl -x $0 ${1+"$@"}

#!perl -w
#line 31

=head1 NAME

untar-config - Provide a new set of configuration files for ZXTM

=head1 SYNOPSIS

B<untar-config>

=head1 DESCRIPTION

This program is used by ZXTM to supply configuration files to a remote
ZXTM machine. It should not be run manually.

=head1 COPYRIGHT

Copyright (C) 2000-2014 Zeus Technology Limited. All rights reserved.

=cut


# Setup our libraries
BEGIN {
   unshift @INC, ( "$ENV{ZEUSHOME}/perl",
                   "$ENV{ZEUSHOME}/admin/lib/perl",
                   "$ENV{ZEUSHOME}/zxtmadmin/lib/perl",
                   "$ENV{ZEUSHOME}/zxtm/lib/perl",
                 );
}

use strict;

use Zeus::ZXTM::ConfUpgrade;
use Zeus::ZXTM::Version qw( ZXTMReleaseVersion );
use Zeus::ZInstall::Common;
use Zeus::ZXTM::Locks qw( ConfigWriteLock );
use Zeus::ZXTM::ConfLink qw( read_conflink get_alternate remove_dir flip_conflink fix_conflink );

# Important definitions 
my ( $newdir, $newdirname, $nowdir, $nowdirname ) = ( undef, undef, undef, undef );
my $upgradedir = "$ENV{ZEUSHOME}/zxtm-new";
my $conflink = "$ENV{ZEUSHOME}/zxtm/conf";
my $zxtmdir = "$ENV{ZEUSHOME}/zxtm";
my $tarpid = undef;

my $log_dir = "$ENV{ZEUSHOME}/zxtm/internal/logs";
my $log_file = "$log_dir/untar-config-" . time() . "-$$";
my $log_fd = undef;

sub touch( $ )
{
   my $file = shift;
   
   if( open TOUCH, ">$file" ) {
      close( TOUCH );
   }
}

sub sanityCheck($)
{
   my( $conf_dir ) = @_;

   if( ! -d $conf_dir ) {
      warn( "Missing config directory: $conf_dir\n" );
      return 0;
   }

   my $ok = 1;
   foreach my $file ( 'settings.cfg', 'users' ) {
      my $path = "$conf_dir/$file";
      if( ! -f $path ) {
         if( -e $path ) {
            warn( "Non-file where file '$path' should be\n" );
         } else {
            warn( "Missing config file: $path\n" );
         }
         $ok = 0;
      }
   }
 
   foreach my $dir ( 
      qw( actionprogs actions appliance bandwidth cloudcredentials custom events 
      extra flipper groups jars licensekeys locations monitors persistence pools 
      protection rate rules scripts services servlets slm ssl ssl/cas ssl/client_keys 
      ssl/dnssec_keys ssl/server_keys supplementarykeys vservers zxtms ) )
   {
      my $path = "$conf_dir/$dir";
      if( ! -d $path ) {
         if( -e $path ) {
            warn( "Non-directory where directory '$path' should be\n" );
         } else {
            warn( "Missing config directory: $path\n" );
         }
         $ok = 0;
      }
   }

   return $ok;
}

# Any args?
my( $upgrade, $partial ) = ( '', '' );

foreach my $param ( @ARGV ) {
   if( $param =~ /--help/i ) {
      print "untar-config should not be run manually.\n";
      exit 0;
   } elsif( $param =~ /--upgrade=(\S+)/ ) {
      $upgrade = $1;
   } elsif( $param =~ /--partial=(\S+)/ ) {
      $partial = $1;
   }
}

# Config is created read/writable for current user only
umask( 0077 );

my( $err, $err_desc ) = ConfigWriteLock()->RunLocked(
   { timeout => 30, code_timeout => 30, kill_timeout => 120 },
   sub {

      Zeus::ZInstall::Common::Mkdir( $log_dir, 0777 );
      $| = 1;
      open( $log_fd, '>', $log_file );

      # Check if we have a valid link to our config directory. Something
      # has gone horrible wrong if this link is missing.
      if( !-l $conflink ) {
         # Maybe it's still a directory, upgrade it to a symlink
         my $err_str = fix_conflink();
         # Try to go on if we fixed the config symlink
         if( $err_str ) {
            print( $log_fd $err_str );
            die $err_str;
         }
         print( $log_fd "Configuration symlink was not pointing to a valid configuration directory".
                        ", the problem is fixed for now, proceeding with un-tarring config. ");
      }

      $nowdirname = read_conflink();
      $nowdir = "$ENV{ZEUSHOME}/zxtm/$nowdirname"; 
      
      # Set the directory path where the new config will be untarred.
      $newdirname = Zeus::ZXTM::ConfLink::get_alternate( $nowdirname );
      if( !defined( $newdirname )) {
         print( $log_fd "Could not determine the configuration directory to keep the new configuration".
                        " '$ENV{ZEUSHOME}/conf' is a symlink to $nowdirname, which isn't a recognized configuration directory\n" );
         die ( "Could not determine the configuration directory to keep the new configuration, ".
              " '$ENV{ZEUSHOME}/zxtm/conf' is a symlink to '$nowdirname', an unrecognized configuration directory." );
      }
      $newdir = "$ENV{ZEUSHOME}/zxtm/$newdirname";

      # Remove any existing dir with the new name
      if( -e $newdir ) {
         print( $log_fd "Removed '$newdir' before untarring new-config into it\n" );
         system( 'rm', '-rf', $newdir );
      }

      # Remove upgrade dir
      if( -e $upgradedir ) {
         print( $log_fd "Removed '$upgradedir'\n" );
         system( 'rm', '-rf', $upgradedir );
      }

      # Log activity
      print( $log_fd "Untar-Config started [" . scalar( localtime() ) . " - " . time . "]\n" );
      print( $log_fd "Command: [$0 @ARGV]\n" );

      # Create temp new config directory
      if( $partial ) {
         print( $log_fd "Creating partial backup directory\n" );
         if( system( 'cp', '-r', $nowdir, $newdir ) ) {
            die( "Failed to copy from '$nowdir' to '$newdir' while handling partial config replication\n" );
         }
         foreach my $dir ( split( ',', $partial ) ) {
            system( 'rm', '-r', "$newdir/$dir" ) if( -d "$newdir/$dir" );
         }
      } else {
         print( $log_fd "Creating empty full backup directory\n" );
         Zeus::ZInstall::Common::Mkdir( $newdir, 0777 ) or die( "mkdir: $!\n" );
      }

      if( !-d $newdir ) {
         print( $log_fd "FATAL: Failed to create new directory '$newdir'\n" );
         die( "Failed to create new directory: '$newdir'" );
      }

      chdir( $newdir ) or die( "Failed to chdir into the newly created directory: $!\n" );

      $SIG{PIPE} = 'IGNORE';

      # Now run the tar binary
      print( $log_fd "Running tar [tar xf -]\n" );
      $tarpid = open( TAR, "|tar xf - >/dev/null 2>&1" );

      if( ! defined( $tarpid ) ) {
         print( $log_fd "FATAL: Failed to run tar: $!\n" );
         die "Problem running tar: $!\n";
      }

      my $buffer;
      for(;;) {
         my $r = sysread( STDIN, $buffer, 4096 );
         last if( !defined( $r ) || $r <= 0 );
         my $p = 0;
         while( $p < $r ) {
            my $w = syswrite( TAR, $buffer, $r - $p, $p );
            last if( !defined( $w ) || ( $w <= 0 ));
            $p += $w;
         }
      }

      # if the tar hangs or spins, close will waitpid() forever
      if( !close( TAR ) || $? ) {
         print( $log_fd "FATAL: Tar failed to complete\n" );
         die( "Unpacking the new configuration failed\n" ) 
      }
      print( $log_fd "Tar extract complete - New config should now be in $newdir\n" );
      $tarpid = undef;

      if( $upgrade ) {
         print( $log_fd "Upgrading configuration\n" );
         Zeus::ZInstall::Common::Mkdir( $upgradedir, 0777 ) or die( "mkdir: $!\n" );
         chdir( $upgradedir ) or die( "chdir $upgradedir failed: $!\n" );
         # Set 'conf' in $ZEUSHOME/zxtm-new to be a link to the new config dir.
         # See comment below.
         symlink( $newdir, 'conf' ) || die( "Creating symlink from '$upgradedir/conf' to '$newdir' failed: $!\n" );
         # Now the directory tree looks like
         # $nowdir = $ZEUSHOME/zxtm/conf_A
         # $newdir = $ZEUSHOME/zxtm/conf_B
         # $upgradedir = $ZEUSHOME/zxtm-new
         # New upgraded conf is a link to $newdir.
         # $ZEUSHOME/zxtm-new/conf -> $ZEUSHOME/zxtm/conf_B where
         # we want the new configuration to live in. 
         # We need to do this because code in ConfUpgrade assumes the configuration
         # directory to be named 'conf'( which is fair ).
         Zeus::ZXTM::ConfUpgrade::upgrade_config( $upgradedir, $upgrade, ZXTMReleaseVersion() );
      }

      # Sanity check the new configuration directory
      if( ! sanityCheck( $newdir ) ) {      
         print( $log_fd "FATAL: New directory failed sanity check, is it a partial configuration replication? $partial\n" );
         if( $partial ) {
            die( "Partial configration update failed ( probably received an invalid tar archive )\n" )
         } else {
            die( "New configuration is incomplete (must be a valid configuration tar file)\n" )
         }
      }

      my $err = flip_conflink(); 
      if( $err ) {
         print( $log_fd "FATAL: $err" );
         # Does the conf link to something valid.
         remove_dir( $newdir );
         die( "Configuration not updated after config replication: $err" )
      } else {
         Zeus::ZXTM::ConfUpgrade::migrate_firewall_rule();
         # Remove the previously used configuration directory.
         remove_dir( $nowdir );
         # and remove temporary dir 'zxtm-new'
         remove_dir( $upgradedir );
      }
     
      if( $partial ) {
         touch( "$ENV{ZEUSHOME}/zxtm/.lastupdate_partial" );
      } else {
         touch( "$ENV{ZEUSHOME}/zxtm/.lastupdate" );
      }

      # All done
      print "Update successful\n";
      print( $log_fd "Untar-Config completed successfully [" . scalar( localtime() ) . " - " . time . "]\n" );
      close( $log_fd );
      $log_fd = undef;
} );

if( $log_fd ) {
   close( $log_fd );
}

system( 'cp', $log_file, "$log_dir/untar-config-last" );

if( $err ) {
   print STDERR "Untar of new config failed: $err_desc\n";
   
   my $err_str = fix_conflink();
   print( STDERR $err_str ) if( defined( $err_str ));

   kill( 9, $tarpid ) if( $tarpid ); # Ensure tar sub-process is dead

   # Check we don't leave round too many logs
   my @other_logs = glob( "$log_dir/untar-config-*" );
   if( scalar( @other_logs ) > 100 ) {
      system( 'rm', $log_file );
   }
   exit -1;
} else {
   system( 'rm', $log_file );
}


