#!/bin/sh
#-----------------------------------------------------------------------------
# sneeze: Rebuild the CASA system areas for 'inhale'
#-----------------------------------------------------------------------------
#
#   Copyright (C) 1993-1997,2001,2003
#   Associated Universities, Inc. Washington DC, USA.
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#   Correspondence concerning CASA should be addressed as follows:
#          Internet email: aips2-request@nrao.edu.
#          Postal address: AIPS++ Project Office
#                          National Radio Astronomy Observatory
#                          520 Edgemont Road
#                          Charlottesville, VA 22903-2475 USA
#
#-----------------------------------------------------------------------------
# Usage: sneeze [-l] [-e <extlist>] [-m <mode>] [-s <seconds>] targets 
#-----------------------------------------------------------------------------
# sneeze rebuilds the CASA system areas performing certain accounting
# functions.  It is intended for the use of 'inhale' rather than for general
# usage.
#
# Options:
#   -e     Serially rebuild the systems corresponding to each "aips_ext" in
#          the blank- or colon-separated list.  If no "-e" option is given
#          sneeze just rebuilds the host's default architecture (as specified
#          in "aipshosts").  An "_" in the extlist signals no extension.
#
#   -l     Log mode - if specified then the output of sneeze will be logged
#          to the file specified by the "sneeze.$HOST.$AIPSEXT.logfile"
#          resource and mailed to the addresses specified by the
#          "sneeze.$HOST.$AIPSEXT.logmail" resource.  If these are not defined
#          the log is sent to $AIPSARCH/sneeze.log and the mail to
#          aips2-inhale@nrao.edu.
#
#   -m     Mode of the rebuild, "incremental" (default), "cumulative",
#          "hybrid", or "base".
#
#   -s     time to wait until starting.  Helpful in avoid simultaneous glish build problems
#
# Status return values correspond to the various phases of the operation
#    0:  success
#    1:  initialization error
#    2:  error rebuilding the system
#
# Notes:
#    1) It is assumed that the code areas have already been brought up-to-date
#       with respect to the slave repositories.
#
# Original: 1993/07/13 by Mark Calabretta, ATNF
# $Id$
#=============================================================================
# Initialize
#-----------------------------------------------------------------------------
# Check that CASAPATH is defined.
  if [ "$CASAPATH" = "" ]
  then
     exec 1>&2
     echo ""
     echo "sneeze: CASAPATH is undefined, abort!"
     exit 1
  fi

# Parse CASAPATH.
  AIPSROOT=`echo $CASAPATH | awk '{print $1}'`
  ARCH=`echo $CASAPATH | awk '{print $2}'`
  SITE=`echo $CASAPATH | awk '{print $3}'`
  HOST=`echo $CASAPATH | awk '{print $4}'`

# Check the accessibility of the AIPSROOT area.
  if [ ! -d "$AIPSROOT" ]
  then
     exec 1>&2
     echo ""
     echo "sneeze: The CASA root directory does not exist or is not"
     echo "        accessible, $AIPSROOT"
     exit 1
  fi

# Check the default architecture.
  if [ "$ARCH" = ARCH -o "$ARCH" = "" ]
  then
     exec 1>&2
     echo ""
     echo "sneeze: The host architecture could not be determined, abort!"
     exit 1
  fi

# Guard against being overwritten.
  case $0 in
  *-)
     ;;
  *)
     ARGS=
     DOLOG=
     EXTLIST=
     while [ "$#" -gt 0 ]
     do
        case $1 in
        -e*)
           case $1 in
           -e)
              shift
              EXTLIST=`echo $1 | sed -e 's/  */:/g'`
              ;;
           *)
              EXTLIST=`echo $1 | sed -e '{s/^-e//;s/  */:/g}'`
              ;;
           esac
           ;;
        -l)
           DOLOG=1
           ARGS="$ARGS $1"
           ;;
        -s)
           shift
           echo "Sleeping $1 seconds before continuing..."
           sleep $1
           echo "continuing"
           shift
           ;;
        *)
           ARGS="$ARGS $1"
           ;;
        esac

        [ "x$2" = "x" ] && break

        shift
     done

     if [ "$EXTLIST" = "" ]
     then
        case $ARCH in
        *_*)
           EXTLIST=`echo $ARCH | sed -e 's/.*_//'`
           ;;
        *)
           EXTLIST="_"
           ;;
        esac
     fi

#    Resolve logging issues.
     LOGFILE=""
     LOGMAIL=""
     LOGMAILER=""
	 EXTLIST=`echo :$EXTLIST: | sed -e 's/::*/::/g'`
     AIPSEXT=`echo $EXTLIST | sed -e '{s/^:://;s/::.*//;}'`
     EXTLIST=`echo $EXTLIST | sed -e "{s/::/:/g;s/^://;s/:$//;}"`

     cp $0 $0-
     if [ "$DOLOG" ]
     then
        aips_ext=$AIPSEXT . $AIPSROOT/casainit.sh

        LOGFILE=`getrc -i sneeze.$HOST.$AIPSEXT.logfile 2> /dev/null`
        LOGMAIL=`getrc -i sneeze.$HOST.$AIPSEXT.logmail 2> /dev/null`
		LOGMAILER=`getrc -i sneeze.$HOST.$AIPSEXT.mailer 2> /dev/null`

        [ "$LOGFILE" = "" ] && LOGFILE=$AIPSROOT/$ARCH/sneeze.log
        [ "$LOGMAIL" = "" ] && LOGMAIL=aips2-inhale@nrao.edu
		[ "$LOGMAILER" = "" ] && LOGMAILER=mail


	     if [ "$LOGMAIL" != "" ]
	     then
	        $0- -e $EXTLIST $ARGS 2>&1 | tee $LOGFILE | $LOGMAILER $LOGMAIL
	        exit 0
	     else
	        exec $0- -e $EXTLIST $ARGS 2>&1 > $LOGFILE
	     fi
	else
		exec $0- -e $EXTLIST $ARGS
	fi
     ;;
  esac


# Set default file creation mode.
  umask 002

# Identify ourselves.
  LOGNAME=${LOGNAME-$USER}

  echo ""
  echo "sneeze: $CASAPATH" 
  echo ""
  echo "sneeze: Execution on $HOST by $LOGNAME commenced at"
  echo "sneeze: `adate`"
  echo "sneeze: `adate -l`"

  echo ""
  echo "sneeze: Command line arguments \"$*\""


# Parse command input.
  DOLOG=""
  EXTLIST="_"
  MODE=incremental
  TARGETS=""

  while [ "$#" -gt 0 ]
  do
     case $1 in
     -e*)
        case $1 in
        -e)
           shift
           EXTLIST=`echo $1 | sed -e 's/  */:/g'`
           ;;
        *)
           EXTLIST=`echo $1 | sed -e '{s/^-e//;s/  */:/g}'`
           ;;
        esac
        ;;
     -l)
        DOLOG=1
        ;;
     -m*)
        case $1 in
        -m)
           shift
           MODE="$1"
           ;;
        *)
           MODE=`echo $1 | sed -e 's/^-m//'`
           ;;
        esac
        ;;
     *)
        TARGETS="$TARGETS $1"
        ;;
     esac

     [ "" = "$2" ] && break

     shift
  done

  [ "$EXTLIST" = "" ] && EXTLIST="_"
  EXTLIST=`echo :$EXTLIST: | sed -e 's/::*/::/g'`

# Redefine CASAPATH.
  AIPSEXT=`echo $EXTLIST | sed -e '{s/^:://;s/::.*//;}'`
  aips_ext=$AIPSEXT . $AIPSROOT/casainit.sh

# Revise ARCH.
  ARCH=`echo $CASAPATH | awk '{ print $2 }'`

# Update EXTLIST.
  EXTLIST=`echo $EXTLIST | \
     sed -e "{s/:$AIPSEXT://g;s/::/:/g;s/^://;s/:$//;}"`

  TARGETS=`echo $TARGETS`
  [ "$TARGETS" = "" ] && TARGETS=allsys


# Define major CASA directories.
  AIPSCODE="$AIPSROOT/code"
  AIPSARCH="$AIPSROOT/$ARCH"
  ARCHTMPD="$AIPSARCH/tmp"

# What is the very latest version?
  NEWVERSN=`cat $AIPSCODE/VERSION | awk '{ print $1 }'`
  NEWMAJOR=`echo $NEWVERSN | awk -F. '{ print $1 }'`
  NEWMINOR=`echo $NEWVERSN | awk -F. '{ print $2 }'`

  DASH=`echo $ARCH | sed -e 's/./-/g'`
  echo ""
  echo "sneeze: Rebuild CASA version $NEWVERSN for $ARCH."
  echo "----------------------------------------------$DASH"

# Ensure that the system areas exist.
  if [ ! -d "$AIPSARCH" ]
  then
     exec 1>&2
     echo ""
     echo "sneeze: $AIPSARCH does not exist, you must run 'configure'"
     echo "to create it, abort!"
     exit 1
  fi

# Get account information.
  AIPS2MGR=`getrc -i account.manager    2> /dev/null`
  AIPS2PRG=`getrc -i account.programmer 2> /dev/null`
  MGRACCNT=`echo $AIPS2MGR | sed -e 's/\..*//'`
  MGRGROUP=`echo $AIPS2MGR | sed -e 's/.*\.//'`
  PRGGROUP=`echo $AIPS2PRG | sed -e 's/.*\.//'`

# Check that we're being run from the right account.
  if [ "$MGRACCNT" != "$LOGNAME" -a "$MGRACCNT" != "" ]
  then
     exec 1>&2
     echo ""
     echo "sneeze: This utility can only be run by $MGRACCNT, not" \
          "$LOGNAME, abort!"
     exit 1
  fi

# Report the amount of free space available for the rebuild.
  echo ""
  echo "sneeze: Available space in the /tmp and $AIPSARCH partitions"
  df /tmp $AIPSARCH


#-----------------------------------------------------------------------------
# Rebuild the system
#-----------------------------------------------------------------------------
  echo ""
  echo "sneeze: Applying system deletions..."

  trap 'echo "" ; \
        echo "sneeze: Cleaning up..." ; \
        cd $AIPSROOT ; \
        rm -f $ARCHTMPD/ax_master ; \
        exit' 1 2 3 15

  cp $AIPSCODE/install/codemgmt/ax_master $ARCHTMPD/ax_master
  chmod u+rwx $ARCHTMPD/ax_master
  if [ "$MODE" = incremental ]
  then
#    Apply deletions for the current version onwards.
     $ARCHTMPD/ax_master -system -s
  else
#    Apply all deletions.
     $ARCHTMPD/ax_master -system -s -c
  fi

  rm -f $ARCHTMPD/ax_master

# Check or set directory ownerships and permissions.
  find $AIPSARCH -type d ! -user  $MGRACCNT \
     -exec echo "Incorrect directory ownership:" {} \;
  find $AIPSARCH -type d ! -group $PRGGROUP -exec chgrp $PRGGROUP {} \;
  find $AIPSARCH -type d ! -perm 2775 -exec chmod ug=rwx,g+s,o=rx {} \;

  cd $AIPSCODE

# Clean up the system areas on cumulative updates.
  if [ "$MODE" != incremental ]
  then
     echo ""
     echo "sneeze: Cleaning up the system areas..."
     gmake -i NODEP=1 cleansys
  fi

# Rebuild the system.
  echo ""
  echo "sneeze: Rebuilding the system..."
  gmake -i $TARGETS

# Mark it as done.
  cd $AIPSARCH
  [ -f LOGFILE ] || touch LOGFILE
  mv -f LOGFILE LOGFILE_
  echo "$NEWVERSN `adate`  ($TARGETS)" | cat - LOGFILE_ > LOGFILE

  [ -f VERSION ] && mv -f VERSION VERSION_
  cp -p $AIPSCODE/VERSION .

  chmod 444 VERSION LOGFILE
  rm -f VERSION_ LOGFILE_


#-----------------------------------------------------------------------------
# Preserve the base system.
#-----------------------------------------------------------------------------
  if [ "$MODE" = base ]
  then
     echo ""

     cd $AIPSROOT

     BASEROOT="$AIPSROOT/base-$NEWMAJOR"
     [ -d "$BASEROOT" ] || mkdir $BASEROOT
     chgrp $PRGGROUP $BASEROOT
     chmod ug=rwx,g+s,o=rx $BASEROOT

     BASESYS=`getrc -i sneeze.base.$ARCH.preserve 2> /dev/null`
     BASESYS=`affirm -a $BASESYS`

     if [ "$BASESYS" != false ]
     then
        echo "sneeze: Preserve the base system."
        echo "---------------------------------"

        echo ""
        echo "sneeze: Copying $AIPSARCH to $BASEROOT/$ARCH..."

#       Use the "h" option to force tar to follow symlinks.
        tar chf - $ARCH | (cd $BASEROOT && tar pvxf -)
     else
        echo "sneeze: Preserve the critical parts of the base system."
        echo "-------------------------------------------------------"

        mkdir $BASEROOT/$ARCH
        chgrp $PRGGROUP $BASEROOT/$ARCH
        chmod ug=rwx,g+s,o=rx $BASEROOT/$ARCH

        echo ""
        echo "sneeze: Copying $AIPSARCH/$SITE to $BASEROOT/$ARCH/$SITE..."

#       Use the "h" option to force tar to follow symlinks.
        tar chf - $ARCH/aipsrc $ARCH/makedefs $ARCH/$SITE | \
           (cd $BASEROOT && tar pvxf -)
     fi

     if [ -d "$BASEROOT/code/install" ]
     then
#       Remake the root directory.
        echo ""
        echo "sneeze: Remaking files in $BASEROOT..."
        cp $AIPSROOT/aipshosts $BASEROOT
        ( CASAPATH="$BASEROOT $ARCH $SITE $HOST" ; \
          export CASAPATH ; \
          gmake -i -C $BASEROOT/code/install aipsroot )
     fi

#    Preserve the base documentation but only if we build it. 
     BASEDOCS=`getrc -i sneeze.base.docs.preserve 2> /dev/null`
     BASEDOCS=`affirm -a $BASEDOCS`
     if [ "$BASEDOCS" != false ]
     then
#       Check that we build the documentation.
        eval `gmake -i VARS=DOCSYS eval_vars`

        if [ "$DOCSYS" = doc ]
        then
           echo "sneeze: Preserve the base documentation."
           echo "----------------------------------------"
 
           echo ""
           echo "sneeze: Copying $AIPSROOT/docs to $BASEROOT/docs..."

#          Use the "h" option to force tar to follow symlinks.
           tar chf - docs | (cd $BASEROOT && tar pvxf -)
        fi
     fi
  fi


#-----------------------------------------------------------------------------
# Wind up.
#-----------------------------------------------------------------------------
  cd $AIPSCODE

# Produce diagnostics on cumulative updates.
  if [ "$MODE" != incremental ]
  then
     echo ""
     echo "sneeze: System diagnostics."
     echo "---------------------------"

     gmake -i -f $AIPSARCH/makedefs diagnostics
  fi

# We're finished with this architecture.
  echo ""
  echo "sneeze: Execution terminated at"
  echo "sneeze: `adate`"
  echo "sneeze: `adate -l`"

# Recurse if necessary.
  if [ "$EXTLIST" != "" ]
  then
     if [ "$DOLOG" != "" ]
     then
#       Find the next AIPSEXT.
        EXTLIST=`echo :$EXTLIST: | sed -e 's/::*/::/g'`
        AIPSEXT=`echo $EXTLIST | sed -e '{s/^:://;s/::.*//;}'`
        EXTLIST=`echo $EXTLIST | sed -e "{s/::/:/g;s/^://;s/:$//;}"`

        aips_ext=$AIPSEXT . $AIPSROOT/casainit.sh
	ARCH=`echo $CASAPATH | awk '{ print $2 }'`

        LOGFILE=`getrc -i sneeze.$HOST.$AIPSEXT.logfile 2> /dev/null`
        LOGMAIL=`getrc -i sneeze.$HOST.$AIPSEXT.logmail 2> /dev/null`
	LOGMAILER=`getrc -i sneeze.$HOST.$AIPSEXT.mailer 2> /dev/null`

        [ "$LOGFILE" = "" ] && LOGFILE=$AIPSROOT/$ARCH/sneeze.log
        [ "$LOGMAIL" = "" ] && LOGMAIL=aips2-inhale@nrao.edu
	[ "$LOGMAILER" = "" ] && LOGMAILER=mail

        if [ "$LOGMAIL" != "" ]
        then
           (exec $0 -e $EXTLIST -l -m $MODE $TARGETS 2>&1 | \
              tee $LOGFILE | $LOGMAILER $LOGMAIL) &
           exit 0
        else
           exec $0 -e $EXTLIST -l -m $MODE $TARGETS 2>&1 > $LOGFILE
        fi
     else
        echo ""
        echo ""
        echo ""
        exec $0 -e $EXTLIST -m $MODE $TARGETS
     fi
  fi


  exit 0
