#!/usr/bin/env perl
#+++++++++++++++++++++++++++++++++++++++++++++++++++++
# 30.01.2002 gmekiffe, active offline
#+++++++++++++++++++++++++++++++++++++++++++++++++++++
# COPYRIGHT (c) 2000 European Southern Observatory
# LICENSE
#
# PROJECT:   VLT Data Flow System
# AUTHOR:    Michele Zamparelli - ESO/DMD/SEG
# CI NUMBER: 
#+++++++++++++++++++++++++++++++++++++++++++++++++++++
$rcs_version = '$Revision: 1.3 $';
#' this for xemacs
$| = 1 ;

sub dielog { 
    local($msg) = $_[0];
    local( $message ) =  "module2-failure: $msg" ;
    shmwrite($shm_id,$message ,0,200) || die "$!" ;
    die $msg."\n";
}

#
# Check the existance of the recipes as indicated by RECIPE_SET in gasgano 
# preferences
#
sub check_gasgano_preferences {
    local( $file) = $_[0]; 
#    print "Working with file=$file\n";
   
    # check if the preference file is there
    dielog "Could not access gasgano preferences file $file \nExiting...\n" if ( ! -r "$file");
    $recipe_set = "" ;
    open(table,$file);
    while($tmp = <table>) {
      if ( $tmp =~ /^RECIPE_SET/ )  {
              $recipe_set .= $tmp ;
#              print "Working with $recipe_set\n";
       }
    }
#    print "End with $recipe_set\n";
    if ($recipe_set !~ /^RECIPE_SET/)  {
#      print "WARNING: NO RECIPE_SET in gasgano preferences file $file\n";
      return;
    }
    $recipe_set =~ s/^RECIPE_SET=\s*// ;
    chop ($recipe_set);
#    print "End with $recipe_set\n";
    foreach ( (split(';', $recipe_set) ) ) {
      $tmp = $_;
#      print "value tmp = $tmp\n";
      $recipe_path = (split('=', $tmp))[1];
#      print "recipe = $recipe_path\n";
      if ( ! -e "$recipe_path") {
            print "WARNING: Could not find recipe file $recipe_path\n";
        }
    }
}

$shm_id = $ARGV[0] ; 
$instrument = $ARGV[1] ; 
$tarfile = $ARGV[2] ;
$offline = $ARGV[3] ;
$updateCalibDbLogfile = "/tmp/ipip$$-updateCalibDb.log";

# last checks first

if (   ( $ENV{MIDASHOME} eq "")  || ( $ENV{MIDVERS} eq "" )  ) { 
    print "MIDASHOME or MIDVERS undefined or wrongly set \n";
    dielog "MIDASHOME or MIDVERS undefined or wrongly set\n";
}

if (   $ENV{DFS_QC1_DIC_DIR} eq "") {
    print "DFS_QC1_DIC_DIR undefined  \n";
    dielog "DFS_QC1_DIC_DIR undefined  \n";
}

if ( !  -d "$ENV{DFS_QC1_DIC_DIR}") {
    print "The directory DFS_QC1_DIC_DIR points to ($ENV{DFS_QC1_DIC_DIR}), does not exist \n";
    dielog "The directory DFS_QC1_DIC_DIR points to ($ENV{DFS_QC1_DIC_DIR}),  does not exist \n";
}

if (   $ENV{DFS_GASGANO_CONFIG_DIR} eq "") {
    print "DFS_GASGANO_CONFIG_DIR undefined  \n";
    dielog "DFS_GASGANO_CONFIG_DIR undefined  \n";
}

if ( !  -d "$ENV{DFS_GASGANO_CONFIG_DIR}") {
    print "The directory DFS_GASGANO_CONFIG_DIR points to ($ENV{DFS_GASGANO_CONFIG_DIR}), does not exist \n";
    dielog "The directory DFS_QC1_DIC_DIR points to ($ENV{DFS_QC1_DIC_DIR}),  does not exist \n";
}

# here we start

print "*" x 30;
print "\nIPIP MODULE TWO $rcs_version\n";
print "Instrument is $instrument\n";
print "Tarfile is $tarfile\n";
sleep 1;
#
# check whether relshow is in the path
#
system "relshow > /dev/null 2>&1";
dielog "relshow not in the path, or something wrong with it\n" if $? !=0;
#
# check whether relshow knows about calibDB
#
print "Checking existence of CalibDB\n";
system "relshow calibDB > /dev/null 2>&1 ";
dielog "database calibDB unknown to msql2\n" if $? !=0;
#
# check whether the msql2 daemon is running
#
print "Checking msql2 daemon runnning\n";
@msqlproc =  `ps -fe | grep msql2d | grep -v grep`;
print "Amount of msql processes running: ".($#msqlproc +1)."\n";
if ( $#msqlproc < 0) { 
    dielog "msql2 is not running\nChek the boot scripts or contact System administrators\n";
}
#
# check the content of the tarfile
# and preemptively delete same files if already existing
#
$destdir = "/tcal";
chdir  $destdir or dielog "Could not change directory to  $destdir\n";
print "Current directory now $destdir\n";
foreach $file (  `zcat $tarfile | tar tf -` ) { 
    chop( $file ); 
    if ( -e "$destdir/$file" && -f "$destdir/$file" ) { 
	unlink "$destdir/$file" ;
    }
}
#
print "Untarring $tarfile\n";
system "zcat $tarfile | tar xf -";
dielog "Could not untar  $tarfile\n" if $? !=0;
#
if ( ! -d $instrument ) { 
    dielog "Tarfile unpacked but $instrument directory not existing\n" if $? !=0;    
}
# putting the dictionaries for QC1 LogWriter in the appropriate place, if available
if (  -d "dic") {
    print "Copying files for QC1LogWriter ($ENV{DFS_QC1_DIC_DIR})\n";
    opendir(qc1logdir, "dic");
    foreach $dic ( readdir(qc1logdir)) { 
	if ( -f "dic/$dic") { 
	    system "/bin/cp -f dic/$dic $ENV{DFS_QC1_DIC_DIR} \n";
	}
    }
}

# putting classification rule files for Gasgano in the appropriate place, if available
if (  -d "gasgano/config") {
    print "Copying classification rule files for Gasgano ($ENV{DFS_GASGANO_CONFIG_DIR})\n";
    opendir(gasganoconfigdir, "gasgano/config");
    foreach $rul ( readdir(gasganoconfigdir)) { 
	if ( -f "gasgano/config/$rul") { 
	    system "/bin/cp -f gasgano/config/$rul $ENV{DFS_GASGANO_CONFIG_DIR} \n";
	    print "Checking gasgano preferences in gasgano/config/$rul \n";
            check_gasgano_preferences "gasgano/config/$rul" ;
	}
    }
}

if ( -d "offline" ) { 
    if ($offline == 1) { 
	print "Copying files for offline installation\n";
 	opendir(dirhndl, "offline");
 	@files = readdir(dirhndl);
 	foreach $file ( @files) { 
          if ( -f "offline/$file") {
 	    $destination = `find $instrument -name $file`;
 	    system "/bin/cp -f offline/$file $destination";
          }
 	}
    }
    system "/bin/rm -fr offline";
} else {
    print "Directory offline is not delivered, nothing to do\n";
}

#
# removing possibly available dic directory
#
if (  -d "dic") {
    system "/bin/rm -fr dic";
    dielog "Could not delete dic directory from /tcal\n" if $? !=0;
}

#
# removing possibly available gasgano directory
#
if (  -d "gasgano") {
    system "/bin/rm -fr gasgano";
    dielog "Could not delete gasgano directory from /tcal\n" if $? !=0;
}

#
# making directories in the /cal area first
#
#foreach ( `find $instrument -type d ` ) {
#    chomp;
#    if ( ! -d "/cal/$_" ) {
#            system "mkdir -p /cal/$_";
#            system "if [ `basename $_` = rec ]; then mkdir -p cal/$_/../cal; fi";
#   }
#}

#
# changing permissions
#
print "Changing permissions to read/write for everyone\n";
system "chmod -R u+rw $instrument" ;
dielog "Could not change permissions\n" if $? !=0;
#
# cleanup the logfile, if existing
#
unlink $updateCalibDbLogfile;
#
#
#
#
#spawn a subprocess to monitor
#
$pid = fork();   die "Fork failed: $!" unless defined $pid;
if ( ! $pid  ) { 
    chdir "/tmp";
    $command = "/bin/ps -fu ".(getpwuid($>))[0] ." | grep updateCalibDb | grep -v grep";
    sleep 2;
    while(1) { 
	@running = `$command`;
	if ($#running == -1) { 
	    exit;
	}
	print ".";
	sleep 20;
    }
}

#
# running updateCalibdb, check on legal files already done in 
# main module
#
print "Running updateCalibDb\n(this may take a while)\n";
system "updateCalibDb -a > $updateCalibDbLogfile 2>&1";
dielog "Could not execute updateCalibDb -a \nPlease check its logfile in $updateCalibDbLogfile\n" if $? >= 100;
if ( $? != 0) { 
    warn "There were warnings from updateCalibDb\nPlease check its logfile in $updateCalibDbLogfile\n";
} else { 
#
# updateCalibDB was successful, cleanup the logfile
#
    unlink $updateCalibDbLogfile;
}
#######################################################

