#!/usr/bin/perl
# script name: postflight
# Purpose:
#    This script is called by the Apple PackageMaker App. after 
#   STEREO/WAVES Client software has been installed.  This script modifies the 
#   .login fie of the csh and one of the possible login files of the bash shell.  
#   these modifications will set environment variables so that the clients can
#   be run.  
# J. Silvis
#
#*****************************************************************************

#
# The location of the target directory, where the client code was installed, 
# is an argument supplied to this script by the Apple PackageMaker App.
$targetDir       = @ARGV[1];
$tmGseClientHome = $targetDir . "/STEREO/TMlib_Client" ;
$home            = $ENV{'HOME'};    

# copy a simple configuration file to the user's home if it doesn't exist.
# or back up the existing one and copy over the newer version
if (!stat("$home/.tmlibrc")) {
    `cp $tmGseClientHome/tmlibrc.new $home/.tmlibrc`;
} else {
    `cp $home/.tmlibrc $home/.tmlibrc.bak`;
    `cp $tmGseClientHome/tmlibrc.new $home/.tmlibrc`;
}

print "tmGseClientHome " . $tmGseClientHome;

#***  Create a timestamp *** 
@timearray = localtime();
$min = @timearray[1];
if ($min <  10) { $min = "0" .  $min; }

$hour = @timearray[2];
if ($hour <  10){$hour = "0" .  $hour;} 

$date = @timearray[3];
if ($date <  10){ $date = "0" .  $date;}  

$mon =(Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)
         [@timearray[4]];
         
$year =  @timearray[5] + 1900;

$timeStamp = $date.$mon.$year." ". $hour . ":" . $min;
#*** time stamp created ****





#
# This section of code will make symlinks to executables in the program 
# files directories.  The smlink will be placed in the  $tmGseClientHome/bin
# dir.  The program executables have the form:
# $tmGseClientHome/programs/excutableName/executableName
#
#
#$delimiter = "/";
#while (glob "$tmGseClientHome/programs/utilities/*") {
#   print "Make Symlink: " . $_  . "\n";
#   @totalPathToProgramName = split(/$delimiter/,$_) ;
#   $nameOfExecutable = @totalPathToProgramName[$#totalPathToProgramName];
#   symlink  $_ . "/" . $nameOfExecutable , "$tmGseClientHome/bin/" . 
#                                                 $nameOfExecutable;
# }

#
# ranlib needs to be run so that code can properly link to 
# the libraries in the *.a files
#
while (glob "$tmGseClientHome/lib/c/*.a") {
   print "ranlib : " . $_  . "\n";
   system(" ranlib " . $_ )
 }

#
# The lines below will be put at the beginning and the end of the 
# commands inserted into the login file.  This script will use them to identify 
# parts of the login file that have been modified by a previous installation
# of the S/WAVES client code.
$BeginLoginConfigCommands = 
    "############### Start STEREO WAVES Client Configuration #############";
$EndLoginConfigCommands = 
    "############### End STEREO WAVES Client Configuration   #############";





#*****************************************************************************
# Make modifications so that the clients will run under the csh shell
#
#*****************************************************************************

#
# Commands to allow STEREO/WAVES clients to run will be placed in the .login file.
$UserCshrc = $home . "/.cshrc";

if (!(-e $UserCshrc )) 
   {
     system("touch " . $UserCshrc);
   }

# Make a copy of the .login file, but do not copy any lines that are from a 
# previous installation of the SWAVES clients.
open(CshrcFilehandle, $UserCshrc);
$tempFile=$home . "/SWAVES_CSH_COMNFIG.junk";
open(tmp,"> " . $tempFile);
while ($line = <CshrcFilehandle>) {
   # The if-block below filters any lines from a previous installation of the 
   # client software.  
   if ($line =~  m/$BeginLoginConfigCommands/ ) 
   {
       until ( $line =~   m/$EndLoginConfigCommands/) 
       {
          $line = <CshrcFilehandle> ;       
        }
       $line = <CshrcFilehandle> ;   
    } 
    print tmp $line; 
} 
#
# Append lines to the login file lines that will allow the SWAVES clients to run.
print tmp $BeginLoginConfigCommands . "\n"; # header intro
print tmp "# The following lines were written by the postflight script \n";
print tmp "# of the package maker that installed the STEREO/WAVES Clients. \n";
print tmp "# Software installed on:  $timeStamp  \n \n";
print tmp "if (\$\?prompt && ! \$\?STEREO_CLIENT_CONFIG) then \n";
print tmp "      setenv STEREO_TMlib_Client_Home ". $tmGseClientHome . "\n";
print tmp "      # \n";
print tmp "      if ( -e \$STEREO_TMlib_Client_Home/bin/TMlib_Startup.csh) then  \n";
print tmp "           source \$STEREO_TMlib_Client_Home/bin/TMlib_Startup.csh \n";
print tmp "      endif \n";
print tmp "      setenv STEREO_CLIENT_CONFIG done \n";
print tmp "endif  \n";
print tmp $EndLoginConfigCommands . "\n";


close CshrcFilehandle;
close tmp; 
rename($tempFile, $UserCshrc);
#*****************************************************************************
# The users .cshrc file now modified to run  STEREO/WAVES Clients under csh
#*****************************************************************************




#*****************************************************************************
# Make modifications so that the clients will run under the bash shell
#
#*****************************************************************************

#*****************************************************************************
#          SELECT CORRECT BASH CONFIG FILE TO MODIFY 
# There are three possible files in bash that play the role of a login file 
# from csh.  (See "Learning the bash shell", C. Newham, Pub O'Reily, p 58).  
# Only one of these files will be run when a bash shell logs in.  The files are 
# searched in order and the highest ranking file is sourced.  The files are in 
# order: .bash_profile, .bash_login and .profile.  
#
# The code below will search for the highest ranking config file and later   
# lines will be append to that config file to allow the SWAVES clients to run.  
# If none of the three files are found a /.bash_profile will be created and used.  
$SelectedConfigFileToChange = $home . "/.bash_profile";
if (!(-e $SelectedConfigFileToChange)) 
{
  $SelectedConfigFileToChange = $home . "/.bash_login";
  if (!(-e $SelectedConfigFileToChange)) 
  {
     $SelectedConfigFileToChange = $home . "/.profile";
       if  (!(-e $SelectedConfigFileToChange)) {
         #
         # None of the standard bash login files exist -> make .bash_profile 
         $SelectedConfigFileToChange = $home . "/.bash_profile";
         open(createBashHandle,"> " . $SelectedConfigFileToChange); 
         print createBashHandle "# This script runs at the login of a bash shell \n\n" ;
         print createBashHandle "source \$HOME/.bashrc \n\n";
         close createBashHandle;
       }
    } 
} 
# create a .bashrc file if none exists so that the source command 
# in .bash_profile (or other bash config file) will not give an error
if (!(-e $home . "/.bashrc")) 
   {
     system("touch " . $home . "/.bashrc");
   }
#
#           CORRECT BASH CONFIG FILE NOW CHOSEN
#*****************************************************************************





# Make a copy of the bash config file (i.e. .bash_profile, .bash_login or .profile)
# that is the target for modification, but do not copy any lines that are from a 
# previous installation of the SWAVES clients.
open(LoginFilehandle,$SelectedConfigFileToChange);
$tempFile=$home . "/SWAVES_BASH_COMNFIG.junk";
open(tmp,"> " . $tempFile);
while ($line = <LoginFilehandle>) {

   # The if-block below filters any lines from a previous installation of the 
   # client software.  
   if ($line =~  m/$BeginLoginConfigCommands/ ) 
   {
       until ( $line =~   m/$EndLoginConfigCommands/) 
       {
          $line = <LoginFilehandle> ;       
        }
       $line = <LoginFilehandle> ;   
    } 
    print tmp $line; 
} 

# Append lines to the login file lines that will allow the SWAVES clients to run.
print tmp $BeginLoginConfigCommands . "\n";  # header intro
print tmp "# The following two lines were written by the postflight script \n";
print tmp "# of the package maker that installed the STEREO/WAVES Clients. \n";
print tmp "# Software installed on:  $timeStamp  \n \n";
print tmp "        export STEREO_TMlib_Client_Home=".$tmGseClientHome . "\n";
print tmp "      # \n";
print tmp "      if test -e \$STEREO_TMlib_Client_Home/bin/TMlib_Startup.sh \n";
print tmp "         then  \n";
print tmp "            source \$STEREO_TMlib_Client_Home/bin/TMlib_Startup.sh \n";
print tmp "      fi \n";
print tmp $EndLoginConfigCommands . "\n";  # signals end of SWAVES modifications

close LoginFilehandle;
close tmp; 
rename($tempFile, $SelectedConfigFileToChange);
#*****************************************************************************
# STEREO/WAVES Clients will now run under bash
#*****************************************************************************
