#!/bin/sh
#
# inspect and commit system configuration in global.cfg

# 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`/../..
    ZEUSHOME=`pwd`
    export ZEUSHOME
    cd $OLD_PWD
fi

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

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

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

#!perl -w #"
#line 30

BEGIN { unshift @INC, "$ENV{ZEUSHOME}/zxtm/lib/perl",
     "$ENV{ZEUSHOME}/zxtmadmin/lib/perl", "$ENV{ZEUSHOME}/perl" }

use Zeus::ZXTM::StorageManager;
use Zeus::ZXTM::SYSConfig qw( GetSettings GetStatus );
use Zeus::ZXTM::LocationUtils qw( getLocalLocation );
use Zeus::WaitLock;
use Zeus::ZXTM::ApplianceUtils   qw( hasApplianceFeature );
use strict;

$| = 1;

use Zeus::ZXTM::StorageManager;
use Zeus::ZXTM::SYSConfig qw( GetSettings GetStatus );
use Zeus::ZXTM::LocationUtils qw( getLocalLocation );

my $lock;

########################################################
# Do nothing if the file exists, 
# meaning VM customization is in progress at the moment.
########################################################
use constant ZXTM_CUSTOMIZATION_FLAG => "/tmp/.zxtm_customization";

END {
   if($lock) {
      $lock->Unlock();
   }
}

# fwd decl.
sub Usage($);

# Used for Zeus internal testing
if( $ENV{ZEUS_INTERNAL_TESTROOT} ) {
   Zeus::ZXTM::SYSConfig::SetRoot( $ENV{ZEUS_INTERNAL_TESTROOT} );
}

my $apply = 0;
my $status = 0;

foreach( @ARGV ) {
   /^--help$|^-h$/   and do { Usage(0); exit 0; };
   /^--apply$|^-a$/  and do { $apply = 1;  next; };
   /^--status$|^-s$/ and do { $status = 1; next; };
   /^--backends/     and do { DumpBackends(); exit 0 };
   # Bad arg. bad bad bad.
   Usage(1);
   exit 1;
}

if( ! scalar @ARGV ) {
   Usage(1);
   exit 1;
}

my $runningLock = "$ENV{ZEUSHOME}/zxtm/.sysconfig-rLock";
my $waitingLock = "$ENV{ZEUSHOME}/zxtm/.sysconfig-wLock";
$lock = new Zeus::WaitLock( $runningLock, $waitingLock );

my ( $err_type, $err_desc ) = $lock->Lock( timeout => 2 );
if($err_type) {
   my $count = 0;
   print("Waiting for Sysconfig lock: lock returned: $err_desc.\nRetrying.\n");
   do {
      ( $err_type, $err_desc ) = $lock->Lock( ( timeout => 10 ) );
      $count++;
      if($err_type) {
	 print("sysconfig: lock retry $count: $err_desc\n");
	 sleep(2);
      }
   } while( $err_type );
   print("$ARGV[0] lock retry $count succeeded\n");
}

if( -f ZXTM_CUSTOMIZATION_FLAG 
      && hasApplianceFeature( "GUEST_CUSTOMIZATION" ) ) {
   print("sysconfig: OS customization in progress, bailing out\n");
   exit( 0 );
}


my $storage = new Zeus::ZXTM::StorageManager;
my $gconf = $storage->getGlobalConfig();
my $sconf = $storage->getSettingsConfig();
my $uconf = $storage->getUsersConfig();
my $security_conf = $storage->getConfig( "security" );

if( !defined( $gconf ) || !defined( $sconf ) ||
    !defined( $uconf ) || !defined( $security_conf ) ) {
   select( undef, undef, undef, 0.25 );
   $gconf ||= $storage->getGlobalConfig();
   $sconf ||= $storage->getSettingsConfig();
   $uconf ||= $storage->getUsersConfig();
   $security_conf ||= $storage->getConfig( "security" );
   if( !defined( $gconf ) ) {
       die "Missing configuration file: global\n";
   }
   if( !defined( $sconf ) ) {
       die "Missing configuration file: settings\n";
   }
   if( !defined( $uconf ) ) {
       die "Missing configuration file: users\n";
   }
   if( !defined( $security_conf ) ) {
       die "Missing configuration file: security\n";
   }
}

foreach my $conf ( $sconf, $uconf, $security_conf ) {
   if( defined( $conf ) ) {
      $conf->setEditLocation( getLocalLocation( $storage ) );
   }
}

my $errors = "";

foreach my $syssetting ( GetSettings() ) {
   next unless $syssetting->managing( $gconf );

   my $config;
   if( $syssetting->conf() eq 'global' ) {
      $config = $gconf;
   } elsif( $syssetting->conf() eq 'settings' ) {
      $config = $sconf;
   } elsif( $syssetting->conf() eq 'users' ) {
      $config = $uconf;
   } elsif( $syssetting->conf() eq 'security' ) {
      $config = $security_conf;
   } else {
      die "Invalid configuration file: " . $syssetting->conf() . "\n";
   }

   my $e = $syssetting->check( $config );
   next if( !$e );

   if( $apply ) {
      $e = $syssetting->apply( $config );
      $e = $syssetting->check( $config ) if( ! $e );
   }
   $errors .= $e;
}

print "<errors>\n$errors</errors>\n";

if( $status ) {
   print "<system>\n";
   GetStatus( $gconf );
   print "</system>\n";
}

exit 0;


# Used by the test system to dump the backends that we support
sub DumpBackends
{
   foreach my $syssetting ( GetSettings() ) {
      print $syssetting->{component} . "\n";
   }
}


sub Usage($) {
   my $errout = shift;
   my $help = <<EOM;
$0 [--help] [--apply] [--status]
   Check that system configuration matches desired config.
   
   --help:   This help (and exit)
   --apply:  Apply current configuration
   --status: Also display system status
EOM
   if( $errout ){
      print STDERR $help;
   } else {
      print $help;
   }
}
