#!/bin/sh
#-----------------------------------------------------------------------------
# inhale: Retrieve and install the latest AIPS++ update
#-----------------------------------------------------------------------------
#
#   Copyright (C) 1992-1997,1999,2000,2001,2002,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 AIPS++ should be addressed as follows:
#          Internet email: casa-feedback@nrao.edu.
#          Postal address: AIPS++ Project Office
#                          National Radio Astronomy Observatory
#                          520 Edgemont Road
#                          Charlottesville, VA 22903-2475 USA
#
#-------------------------------------------------------------------------------------
# Usage: inhale [-b] [-c|-m] [-D] [-d] [-l] [-n] [-P] [-R NAME] [-r #] [-w #] [binary]
#               [-cvsup data | docs | all]
#-------------------------------------------------------------------------------------
# inhale retrieves the latest AIPS++ update from the master ftp directories on
# aips2.nrao.edu.  It is invoked regularly as a cron job.
#
# Options:
#   -b     Use the most recently "blessed" release.  Useful for sites
#          that wish to track development but that also require stable
#          releases.
#   -c     Force a cumulative update.
#   -D     Fetch the latest version which has passed the test suite.
#   -d     If the "-n" option is specified, don't remake the "docsys" target.
#          Has no effect if "-n" was not specified.  Note that even if
#          documentation compilation is defeated via the DOCSYS variable in
#          "makedefs" this option may still be useful in preventing "docsys"
#          from being recorded in the LOGFILE entry for the rebuild.
#   -l     Latchkey mode; fetch latchkey updates (if any) together with any
#          other updates intended for general distribution.
#   -m     Do a "mixed" update: (mostly) incremental inhale, cumulative sneeze.
#   -n     Don't remake the system (allsys).  The "install" and "docsys"
#          targets will still be remade; see also the "-d" option.
#   -P     Use passive mode when doing FTP. Useful for firewalls etc. The
#          FTP client being used must support passive mode.
#   -R <NAME> instead of downloading the default distribution, get the
#          one called <NAME>.
#   -r #   Maximum number of ftp attempts, default 12.
#          Set this to zero to circumvent the ftp.
#   -w #   Set retry interval for the ftp in seconds, default 900.
#   binary This retrieves the latest stable/linux_gnu binary from aips2.nrao.edu
#          it sets the -b and -n options so a build will not happen.
#
#   -cvsup data | docs | all  Uses cvsup to retrieve latest data or docs or both
#          from AIPS++ central.  Note you must have cvsup either set using an aipsrc
#          variable or in the path.
#
# Status return values correspond to the various phases of the operation
#    0:  success
#    1:  initialization error
#    2:  initial ftp error
#    3:  main ftp error
#    4:  error extracting or installing the new RCS files
#    5:  error checking out the new code
#    6:  error rebuilding the system
#
# Notes:
#    1) tar will not overwrite files which don't have write permission,
#       regardless of the permission on the parent directory.  Therefore it is
#       necessary to change the permissions explicitly.
#
#    2) The incremental (and cumulative) update files contain the VERSION file
#       for the *preceeding* version.  This is used in multi-increment
#       updates.
#
# The $MSTRFTPD/VERSION file contains the major and minor version numbers of
# the most recent incremental update.
#
# Original: 1992/04/07 by Mark Calabretta, ATNF
# $Id$
#=============================================================================
# Initialize
#-----------------------------------------------------------------------------
# Name of the master ftp machine and area.
  MASTERHOST="aips2.nrao.edu"
  MSTRFTPD="/pub/master"

# Guard against being overwritten.
  case $0 in
  *-)
     ARGS=$*
     ;;
  *)
     cp $0 $0-
     exec $0- $*
     ;;
  esac

# Identify ourselves.
  HOST=`uname -n | sed -e 's/\..*//'`
  LOGNAME=${LOGNAME-$USER}

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

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

# Check that CASAPATH is defined.
  if [ "$CASAPATH" = "" ] ; then
     exec 1>&2
     echo ""
     echo "inhale: CASAPATH is undefined, abort!"
     exit 1
  fi

# Get the site name.
  SITE=`echo $CASAPATH | awk '{print $3}'`
# And its architecture.
  ARCH=`echo $CASAPATH | awk '{print $2}'`

# Produce a status report.
  echo ""
  echo "inhale: Current status of the $SITE installation"
  avers -l

# Determine the AIPS++ root directory.
  AIPSROOT=`echo $CASAPATH | awk '{print $1}'`

# Check the accessibility of the AIPSROOT area.
  if [ ! -d "$AIPSROOT" ]
  then
     exec 1>&2
     echo ""
     echo "inhale: The AIPS++ root directory does not exist or is"
     echo "        not accessible, $AIPSROOT"
     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 this script is being run from the right account.
  if [ "$MGRACCNT" != "$LOGNAME" -a "$MGRACCNT" != "" ]
  then
     exec 1>&2
     echo ""
     echo "inhale: This script can only be run by $MGRACCNT, not" \
          "$LOGNAME, abort!"
     exit 1
  fi

# Set default file creation mode.
  umask 002

# Parse command input.
  BLESSED=""
  RELEASE=
  MODE=incremental
  DINKUM=
  DOCSYS=docsys
  TARGETS=allsys
  LATCHKEY=
  FTPLIMIT=12
  FTPINTVL=900
  PASSIVEFTP=
  BINARY=
  USECVSUP=

  while [ "$#" -gt 0 ]
  do
     case $1 in
     -b)
        BLESSED=1
        ;;
     binary)
        BINARY=1
        TARGETS=install
        BLESSED=1
        ;;
     -c)
        MODE=cumulative
        ;;
     -cvsup)
         shift
	 USECVSUP=1
	 CVSUPGET=$1
         ;;
     -D)
        DINKUM=dinkum
        ;;
     -d)
        DOCSYS=""
        ;;
     -m)
        MODE=hybrid
        ;;
     -n)
        TARGETS=install
        ;;
     -P)
        PASSIVEFTP=yes
        ;;
     -l)
        LATCHKEY=1
        ;;
     -R*)
        case $1 in
        -R)
           shift
           RELEASE="$1"
           ;;
        *)
           RELEASE=`echo $1 | sed -e 's/^-R//'`
           ;;
        esac
        MSTRFTPD=`echo $MSTRFTPD | sed "s/master$/versions\/$RELEASE\/master/"`
        ;;
     -r*)
        case $1 in
        -r)
           shift
           FTPLIMIT="$1"
           ;;
        *)
           FTPLIMIT=`echo $1 | sed -e 's/^-r//'`
           ;;
        esac
        ;;
     -w*)
        case $1 in
        -w)
           shift
           FTPINTVL="$1"
           ;;
        *)
           FTPINTVL=`echo $1 | sed -e 's/^-w//'`
           ;;
        esac
        ;;
     *)
        exec 1>&2
        echo ""
        echo "Usage: inhale [-b|-c|-m] [-d] [-n] [-l] [-P] [-r #] [-w #] binary"
        exit 1
        ;;
     esac

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

     shift
  done

  if [ "$TARGETS" != allsys ]
  then
     [ "$DOCSYS" = "docsys" ] && TARGETS="$TARGETS docsys"
  fi

# Report the amount of free space available for the update.
  echo ""
  echo "inhale: Available space in the /tmp and $AIPSROOT partitions"
  df /tmp $AIPSROOT

# Define major AIPS++ directories.
  AIPSLAVE="$AIPSROOT/slave"
  AIPSCODE="$AIPSROOT/code"

# Create the slave directory if necessary.
  if [ ! -d "$AIPSLAVE" ]
  then
     mkdir $AIPSLAVE
     if [ "$?" != 0 ]
     then
        exec 1>&2
        echo ""
        echo "inhale: Couldn't create $AIPSLAVE, abort!"
        exit 1
     fi

#    Give it the correct group ownership.
     chgrp $MGRGROUP $AIPSLAVE

#    Set directory permissions.
     chmod ug=rwx,g+s,o=rx $AIPSLAVE

     echo ""
     echo "inhale: Created $AIPSLAVE."
  fi

# Create the work area.
  SLAVTMPD=$AIPSLAVE/tmp

# Auto cleanup.
  trap 'echo "" ; \
        echo "inhale: Cleaning up..." ; \
        cd $AIPSROOT ; \
        rm -rf $SLAVTMPD ; \
        exit' 0 1 2 3 15

# Move into the work area.
  if [ "$FTPLIMIT" -gt 0 ]
  then
     [ -d "$SLAVTMPD" ] && rm -rf $SLAVTMPD

     mkdir $SLAVTMPD
     if [ "$?" != 0 ]
     then
        exec 1>&2
        echo ""
        echo "inhale: Couldn't create $SLAVTMPD, abort!"
        exit 1
     fi
  else
#    The work area should already exist.
     if [ ! -d "$SLAVTMPD" ]
     then
        exec 1>&2
        echo ""
        echo "inhale: ftp defeated but $SLAVTMPD doesn't exist, abort!"
        exit 1
     fi
  fi
  cd $SLAVTMPD

# Get the user name.
  USERNAME=$LOGNAME@


#-----------------------------------------------------------------------------
# Initial ftp sequence: get status information from the master
#-----------------------------------------------------------------------------
  if [ "$FTPLIMIT" -gt 0 ]
  then
     echo ""
     echo "inhale: Connect to $MASTERHOST and get status information."

#    Create a file containing commands for ftp.
     echo "open $MASTERHOST" > ftpcommands
     echo "user ftp $USERNAME" >> ftpcommands
     if [ -n "$PASSIVEFTP" ]
     then
        echo "passive" >> ftpcommands
     fi
     echo "cd $MSTRFTPD" >> ftpcommands
     echo "ls master-*.tar.gz masterdir" >> ftpcommands
     if [ "$DINKUM" ]
     then
#       Get the most recent version which passed the test suite.
        echo "get DINKUM VERSION" >> ftpcommands
     else
        echo "get VERSION" >> ftpcommands
     fi
     echo "get BLESSED" >> ftpcommands
     echo "quit" >> ftpcommands
  else
#    The update files must have been fetched manually.
     echo ""
     echo "inhale: I assume that you have already fetched the update files."
     if [ ! -f VERSION ]
     then
        exec 1>&2
        echo ""
        echo "No VERSION file present in $SLAVTMPD, abort!"
        exit 2
     fi
#      touch sitedir
     ls master-*.tar.gz > masterdir
  fi

# Connect to the master host and get a directory listing.
  FTPCOUNT=1
  while [ "$FTPCOUNT" -le "$FTPLIMIT" ]
  do
     ftp -in < ftpcommands

     if [ -f VERSION ]
     then
#       Success.
        break
     elif [ "$FTPCOUNT" = "$FTPLIMIT" ]
     then
        exec 1>&2
        echo ""
        echo "inhale: Failed to get a directory listing and VERSION"
        echo "        file from $MSTRFTPD on"
        echo "        $MASTERHOST after $FTPLIMIT attempts with a"
        echo "        wait interval of $FTPINTVL seconds.  Abort!"
        exit 2
     fi

#    Try again in a while.
     echo "inhale: ftp connection attempt $FTPCOUNT failed," \
          "try again in $FTPINTVL seconds..."
     echo ""
     FTPCOUNT=`expr $FTPCOUNT + 1`
     sleep $FTPINTVL
  done

# Fetch latchkey updates?
  mv VERSION VERSION_
  if [ "$LATCHKEY" = "" ]
  then
     sed -n -e '1p' VERSION_ > VERSION
  else
     sed -n -e '$p' VERSION_ > VERSION
  fi
  rm -f VERSION_

# Parse the VERSION file.
  if [ ! -f "$AIPSLAVE/VERSION" ]
  then
     echo ""
     echo "inhale: No VERSION file in $AIPSLAVE,"
     echo "        will install base release."

     OLDMAJOR="-"
     OLDMINOR=000
     MODE=base
  else
#    Find the previous version.
     OLDVERSN=`cat $AIPSLAVE/VERSION | awk '{print $1}'`
     OLDMAJOR=`echo $OLDVERSN | awk -F. '{print $1}'`
     OLDMINOR=`echo $OLDVERSN | awk -F. '{print $2}'`

     cmp -s VERSION $AIPSLAVE/VERSION
     if [ "$?" = 0 -a \( "$MODE" != cumulative -o "$OLDMINOR" = 000 \) ]
     then
        echo ""
        echo "inhale: The master source code had not changed."

        cd $AIPSLAVE
        [ -f LOGFILE ] || touch LOGFILE
        mv -f LOGFILE LOGFILE_
        echo "$OLDVERSN `adate`  (unchanged)" | cat - LOGFILE_ > LOGFILE
        chmod 444 LOGFILE
        rm -f LOGFILE_

        rm -rf $SLAVTMPD
        trap 0 1 2 3 15

        exit 0
     fi
  fi

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

  MAJMIN="$NEWMAJOR.$NEWMINOR"

# New major release?
  if [ "$NEWMINOR" = - ]
  then
     exec 1>&2
     echo ""
     echo "inhale: Production of base release $NEWMAJOR is in progress."
     exit 2
  elif [ "$NEWMAJOR" != "$OLDMAJOR" ]
  then
     echo ""
     echo "inhale: Installing new base release - $NEWMAJOR."
     MODE=base
  fi

# Check that we got a directory listing.
  if [ ! -f masterdir ]
  then
     exec 1>&2
     echo ""
     echo "inhale: Failed to get a directory listing from the master, abort!"
     exit 2
  fi

# Check to see if we only want a "blessed" version.
# I'm sure this could still use a tweak or two.
  if [ "$BLESSED" != "" ]
  then
     echo ""
     echo "inhale: Blessed inhale requested...checking availability."

#
# Original behaviour was to grab the base release after an uprev, this
# is not particularly desireable since the uprev isn't necessarily stable.
# So I've commented out base release test, so the base release won't be
# loaded until after a stable has been declared (I hope). wky 2001/05/09
#     if [ "$MODE" = base ]
#     then
#        echo "inhale: Blessed request overridden by new base release."
#     elif [ -f BLESSED ]
     if [ -f BLESSED ]
     then
        BLESSEDVERSN=`sed 's/#.*//' BLESSED | \
         awk "{ for (i = 2; i <= NF; i++)
                if (\\$i == \"ALL\" || \\$i == \"$ARCH\") {
                   blessed = \\$1
                   next
                }
              }
              END { print blessed }"`

        if [ "$BLESSEDVERSN" != "" ]
        then
           BLESSEDMAJOR=`echo $BLESSEDVERSN | awk -F. '{print $1}'`
           BLESSEDMINOR=`echo $BLESSEDVERSN | awk -F. '{print $2}'`

           if [ "$BLESSEDMINOR" -le "$OLDMINOR" -a \
                "$BLESSEDMAJOR" -eq "$OLDMAJOR" ]
           then
              echo "inhale: Nothing to do...no new blessings."
              echo "        Current version: $OLDVERSN"
              echo "        Blessed version: $BLESSEDVERSN"
              cd $AIPSLAVE
              [ -f LOGFILE ] || touch LOGFILE
              mv -f LOGFILE LOGFILE_
              echo "$OLDVERSN `adate`  (unchanged)" | cat - LOGFILE_ > LOGFILE
              chmod 444 LOGFILE
              rm -f LOGFILE_
              rm -rf $SLAVTMPD
              trap 0 1 2 3 15
              exit 0
           fi

           if [ "$BLESSEDMAJOR" -lt "$NEWMAJOR" ]
           then
              echo "inhale: Last blessing was for base release $BLESSEDMAJOR."
              echo "        IGNORING BLESSINGS!"
           else
              echo "inhale: Using blessed version $BLESSEDVERSN"
              NEWVERSN="$BLESSEDVERSN"
              NEWMAJOR=`echo $NEWVERSN | awk -F. '{print $1}'`
              NEWMINOR=`echo $NEWVERSN | awk -F. '{print $2}'`
              MAJMIN="$NEWMAJOR.$NEWMINOR"
           fi
        else
#          Should I do this, or just default to a normal inhale?
#          I'll be conservative/paranoid for now and abort the inhale....
           exec 1>&2
           echo "inhale: Blessed versions exist, but I can't figure out which"
           echo "        which one to use--check the BLESSED file's syntax!"
           exit 2
        fi
     else
        echo "inhale: No blessed versions exist, defaulting to normal inhale."
     fi
  fi

# Remove any extraneous information from masterdir.
  cp masterdir masterdir_
  sed -e 's/.*\(master-.*.tar.gz\).*/\1/' masterdir_ > masterdir
  rm -f masterdir_

# Decide what to fetch - the order of the files in $FILES is important.
  FILES=""
  if [ "$MODE" = base ]
  then
#    Get the latest base release.
     BASEFILE=`egrep "master-$NEWMAJOR.000.tar.gz" masterdir`
     if [ "$BASEFILE" = "" ]
     then
        exec 1>&2
        echo ""
        if [ "$FTPLIMIT" -gt 0 ]
        then
           echo "inhale: No base release file in $MSTRFTPD"
           echo "        Distribution system error, abort!"
        else
           echo "inhale: No base release file in $SLAVTMPD, abort!"
        fi
        exit 2
     fi

     FILES="$BASEFILE"
  elif [ "$MODE" = incremental -o "$MODE" = hybrid ]
  then
#    Find the latest incremental updates.
     MINOR=`expr $OLDMINOR + 1001 | sed -e 's/^1//'`
     while [ "$MINOR" -le "$NEWMINOR" ]
     do
        FILE="master-$NEWMAJOR.$MINOR.tar.gz"
        if [ "`grep $FILE masterdir`" != "" ]
        then
           FILES="$FILES $FILE"
        else
           echo ""
           if [ "$FTPLIMIT" -gt 0 ]
           then
              echo "inhale: $FILE is missing in $MSTRFTPD"
           else
              echo "inhale: $FILE is missing in $SLAVTMPD"
           fi
           echo "        Resorting to a cumulative update."

           FILES=""
           MODE=cumulative
           break
        fi

        MINOR=`expr $MINOR + 1001 | sed -e 's/^1//'`
     done
  fi

# Check that the cumulative update file exists.
  if [ "$MODE" = cumulative ]
  then
     CUMLFILE=`egrep "master-$MAJMIN.ALL.tar.gz" masterdir`
     if [ "$CUMLFILE" = "" ]
     then
        exec 1>&2
        echo ""
        if [ "$FTPLIMIT" -gt 0 ]
        then
           echo "inhale: No cumulative update file in $MSTRFTPD"
           echo "        Distribution system error, abort!"
        else
           echo "inhale: No cumulative update file in $SLAVTMPD, abort!"
        fi
        exit 2
     fi

     FILES="$FILES $CUMLFILE"
  fi

  # Add the blessed binary to the files list
  if [ "$BINARY" ]
  then
     FILES="$FILES .blessed-binary-$MAJMIN.tar.gz"
  fi

# Log information.
  if [ "$FILES" != "" ]
  then
     echo ""
     echo "inhale: The following file(s) are required for the update:"
     for FILE in $FILES
     do
        echo "        $FILE"
     done
  else
     exec 1>&2
     echo ""
     echo "inhale: Inconsistency over what files to fetch, abort!"
     exit 2
  fi


#-----------------------------------------------------------------------------
# Main ftp sequence: get the updates from the master
#-----------------------------------------------------------------------------
# Create a file containing commands for ftp to bring home the bacon.
  if [ "$FTPLIMIT" -gt 0 ]
  then
     echo ""
     echo "inhale: Reconnect to $MASTERHOST and get them."

     echo "open $MASTERHOST" > ftpcommands
     echo "user ftp $USERNAME" >> ftpcommands
     if [ -n "$PASSIVEFTP" ]
     then
        echo "passive" >> ftpcommands
     fi
     echo "verbose" >> ftpcommands
     echo "binary" >> ftpcommands
     echo "hash" >> ftpcommands
     echo "cd $MSTRFTPD" >> ftpcommands
     echo "get CHKSUM" >> ftpcommands
     for FILE in $FILES
     do
        echo "get $FILE" >> ftpcommands
     done
     echo "quit" >> ftpcommands

#    Fetch the update files from the master.
     FTPCOUNT=1
     while [ "$FTPCOUNT" -le "$FTPLIMIT" ]
     do
        ftp -in < ftpcommands

        if [ -f CHKSUM ]
        then
#          Checksum verification.
#  Hey Don't forget to add the binary file check sum
#
           FETCH=""
           for FILE in $FILES
           do
              if [ -f "$FILE" ]
              then
                 SUM0=`grep $FILE CHKSUM | awk '{print $1}'`
                 SUM1=`cksum $FILE | awk '{print $1}'`
                 [ "$SUM1" = "$SUM0" ] && continue
                 rm -f $FILE
              fi

#             A missing or corrupted file.
              FETCH="$FETCH $FILE"
           done

#          Everything ok?
           [ "$FETCH" = "" ] && break

#          Inform the spectators.
           echo ""
           echo "inhale: The following file(s) were not received in" \
                "good order:"
           for FILE in $FETCH
           do
              echo "        $FILE"
           done

           if [ "$FTPCOUNT" -lt "$FTPLIMIT" ]
           then
              echo ""
              echo "inhale: Reconnecting to $MASTERHOST to try again..."
           fi

#          Update the ftp command script.
           if [ "$FETCH" != " $FILES" ]
           then
              echo "open $MASTERHOST" > ftpcommands
              echo "user ftp $USERNAME" >> ftpcommands
              if [ -n "$PASSIVEFTP" ]
              then
                 echo "passive" >> ftpcommands
              fi
              echo "verbose" >> ftpcommands
              echo "binary" >> ftpcommands
              echo "hash" >> ftpcommands
              echo "cd $MSTRFTPD" >> ftpcommands
              echo "get CHKSUM" >> ftpcommands
              for FILE in $FETCH
              do
                 echo "get $FILE" >> ftpcommands
              done
              echo "quit" >> ftpcommands
           fi
        elif [ "$FTPCOUNT" -lt "$FTPLIMIT" ]
        then
#          Complete failure, try again in a while.
           echo "inhale: ftp connection attempt $FTPCOUNT failed," \
                "try again in $FTPINTVL seconds..."
           echo ""
           sleep $FTPINTVL
        fi

        FTPCOUNT=`expr $FTPCOUNT + 1`
     done

     if [ "$FTPCOUNT" -gt "$FTPLIMIT" ]
     then
        exec 1>&2
        echo ""
        echo "inhale: Failed to fetch the update files from $MSTRFTPD on"
        echo "        $MASTERHOST after $FTPLIMIT attempts with a"
        echo "        wait interval of $FTPINTVL seconds.  Abort!"
        exit 3
     fi
  else
     echo ""
     echo "inhale: Using prefetched files."
  fi

# EXIT HERE WHEN TESTING!
#   exit

#-----------------------------------------------------------------------------
# Extract and install the update files
#-----------------------------------------------------------------------------
  echo ""
  echo "inhale: Extract and install the update files."
  echo "---------------------------------------------"

# New base release?  Start from scratch.
  if [ "$MODE" = base ]
  then
     echo ""
     echo "inhale: New base release, deleting slave and code trees for" \
          "version $OLDMAJOR..."

     cd $AIPSLAVE
     mv $SLAVTMPD $AIPSROOT/slavetmp$$
     rm -rf $AIPSLAVE/* $AIPSLAVE/.??*
     mv $AIPSROOT/slavetmp$$ $SLAVTMPD

     cd $AIPSCODE
     rm -rf $AIPSCODE/* $AIPSCODE/.??*
  fi

# Extract each update in the correct sequence.
  for FILE in $FILES
  do
     cd $SLAVTMPD
# If we got the binary we need to unpack in $AIPSROOT
     if [ "$FILE" = .blessed-binary-$MAJMIN.tar.gz ]
     then
	cd $AIPSROOT
     fi


     echo ""
     echo "inhale: Extracting $FILE..."

#    The tar log is filtered to reduce excess verbiage.
     exec 3>&1
     TARSTAT=`(gunzip --force --stdout $SLAVTMPD/$FILE | ((tar pmvxf - ; echo $? >&4) | \
        sed -e 's#^.*master/#master/#' \
            -e 's#\(.*/\)\([^/]*\)#\1 \2#' \
            -e 's# bytes, .*# bytes#' | \
        awk '{
               if ($1 != prev) {
                  print $1 ;
                  prev = $1 ;
               }
               $1 = "      "
               print
            }' 1>&3)) 4>&1`
     if [ "$TARSTAT" = 1 ]
     then
        exec 1>&2
        echo ""
        echo "inhale: Failed to untar $FILE, abort!"
        exit 4
     fi

#    Finished with the distribution file.
     rm -f $FILE

#    No need to do any of this other stuff if we're a binary inhale.
     if [ "$FILE" = .blessed-binary-$MAJMIN.tar.gz ]
     then
        cd $SLAVTMPD
	break;
     fi

#    Change it to slave code.
     mv master slave

#    Check for a VERSION file.
     if [ ! -f slave/VERSION ]
     then
        exec 1>&2
        echo ""
        echo "inhale: $FILE does not contain a VERSION file."
        echo "        Distribution error, abort!"
        exit 4
     fi

#    Get the current VERSION file (for multi-increment updates).
     mv -f slave/VERSION $AIPSLAVE

#    Get the current version number.
     INCVERSN=`cat $AIPSLAVE/VERSION | awk '{print $1}'`
     INCMAJOR=`echo $INCVERSN | awk -F. '{print $1}'`
     INCMINOR=`echo $INCVERSN | awk -F. '{print $2}'`
     INCFIXES=`echo $INCVERSN | awk -F. '{print $3}'`

#    Apply deletions/renames.
     if [ -f $SLAVTMPD/slave/install/codemgmt/ax_master,v ]
     then
        echo ""
        echo "inhale: Applying deletions/renames to version $INCVERSN..."

        co $SLAVTMPD/slave/install/codemgmt/ax_master,v $SLAVTMPD/ax_master
        chmod u+rwx $SLAVTMPD/ax_master
        if [ "$MODE" = cumulative -o "$MODE" = base ]
        then
#          Apply all deletions/renames.
           $SLAVTMPD/ax_master -slave -s -c
        else
#          Apply deletions/renames for this version only.
           $SLAVTMPD/ax_master -slave -s
        fi

        rm -f $SLAVTMPD/ax_master
     fi

#    Get the new version number.
     if [ "$MODE" != base ]
     then
        INCMINOR=`expr $INCMINOR + 1001 | sed -e 's/^1//'`
     fi
     INCVERSN="$INCMAJOR.$INCMINOR.$INCFIXES"

#    Prepare the slave directory for receiving the update.
     for ENTRY in `find slave -type f -print`
     do
        if [ -f "$AIPSROOT/$ENTRY" ]
        then
           chmod u+w "$AIPSROOT/$ENTRY" 2> /dev/null || \
              rm -f "$AIPSROOT/$ENTRY"
        fi
     done

#    Merge the new with the old, including the new VERSION file.
     echo ""
     echo "inhale: Updating slave repository to version $INCVERSN..."
     tar cf - slave | ( cd $AIPSROOT ; tar pmxf - )
     if [ "$?" != 0 ]
     then
        exec 1>&2
        echo ""
        echo "inhale: Installation failed - may be incomplete, abort!"
        exit 4
     fi

#    Update the log file.
     cd $AIPSLAVE
     [ -f LOGFILE ] || touch LOGFILE
     mv -f LOGFILE LOGFILE_
     echo "$INCVERSN `adate`  ($MODE)" | cat - LOGFILE_ > LOGFILE

     chmod 444 LOGFILE
     rm -f LOGFILE_

#    Clean it away.
     rm -rf $SLAVTMPD/slave
  done

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

# Mark it as done.
  cd $AIPSLAVE
  if [ "$MODE" != base ]
  then
      if [ "$BLESSED" != "" ]
      then
          # VERSION file which was downloaded from the master
          # ftp directory may no longer match blessed source,
          # so we construct one from the new slave VERSION file
          rm -f $SLAVTMPD/VERSION
          mv VERSION VERSION_
          sed -e "s/[^.]*\.[^.]*\(\..*\)/$NEWVERSN\1/" VERSION_ > VERSION
      else
          [ -f VERSION ] && mv -f VERSION VERSION_
          mv -f $SLAVTMPD/VERSION .
      fi
      echo ""
      echo "Marked: `cat VERSION`"
  fi

  chmod 444 VERSION
  rm -f VERSION_

# Clean up unless we'll be calling ourself again with prefetched files.
  if [ "$MODE" != base -o "$NEWMINOR" = 000 -o "$FTPLIMIT" -gt 0 ]
  then
     rm -rf $SLAVTMPD
  fi

  trap 0 1 2 3 15


#-----------------------------------------------------------------------------
# Update the code areas.
#-----------------------------------------------------------------------------
  echo ""
  echo "inhale: Update the code areas."
  echo "------------------------------"

# Create the rcs symbolic link required by the AIPS++ makefiles.
  cd $AIPSROOT
  if [ ! -d rcs ]
  then
     ln -s slave rcs
     chgrp $MGRGROUP rcs
     echo ""
     echo "inhale: Created symlink rcs -> slave in $AIPSROOT."
  fi

# Ensure all code directories exist.
  mktree -l -r -s

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

# Ensure that RCS is installed here.
  for DIREX in `echo $PATH | sed -e 's/:/ /g'` ""
  do
     [ -f "$DIREX/co" ] && break
  done

  if [ "$DIREX" = "" ]
  then
     exec 1>&2
     echo ""
     echo "inhale: RCS does not appear to be available (check your" \
          "PATH), abort!"
     exit 5
  fi

# Now the code areas.
  cd $AIPSCODE

# Clean up the code areas on cumulative and hybrid updates.
  if [ "$MODE" = cumulative -o "$MODE" = hybrid ]
  then
     echo ""
     echo "inhale: Cleaning up the code areas..."
     gmake NODEP=1 cleancode
  fi

# Checkout all new code.
  echo ""
  echo "inhale: Updating the code areas..."
  gmake NODEP=1 chkout

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

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

  chmod 444 VERSION LOGFILE
  rm -f VERSION_ LOGFILE_


# Preserve the base version of the slave and code if a new major release.
  if [ "$MODE" = base ]
  then
     echo ""

     BASESLAV=`getrc -i inhale.base.slave.preserve 2> /dev/null`
     BASECODE=`getrc -i inhale.base.code.preserve  2> /dev/null`
     BASESLAV=`affirm -a $BASESLAV`
     BASECODE=`affirm -a $BASECODE`

     cd $AIPSROOT
     BASEROOT="$AIPSROOT/base-$NEWMAJOR"

     if [ "$BASESLAV" != false -o "$BASECODE" != false ]
     then
        [ -d $BASEROOT ] || mkdir $BASEROOT
        chgrp $PRGGROUP $BASEROOT
        chmod ug=rwx,g+s,o=rx $BASEROOT
     fi

     if [ "$BASESLAV" != false ]
     then
        echo "inhale: Copying $AIPSLAVE to $BASEROOT/slave..."
        tar cf - slave  | (cd $BASEROOT && tar pvxf -)
     else
        echo "inhale: Preservation of the slave directories was disabled."
     fi

     echo ""
     if [ "$BASECODE" != false ]
     then
        echo "inhale: Copying $AIPSCODE to $BASEROOT/code..."
        tar cf - code | (cd $BASEROOT && tar pvxf -)

#       Delete all RCS symlinks.
        echo ""
        echo "inhale: Deleting RCS symlinks from $BASEROOT/..."
        cd $BASEROOT
        find code -name RCS -type l -exec rm -f {} \;
     else
        echo "inhale: Preservation of the code directories was disabled."
     fi

     if [ "$BASESLAV" != false -a "$BASECODE" != false ]
     then
        echo ""
        echo "inhale: Recreating RCS symlinks for $BASEROOT/..."
        cd $BASEROOT
        ln -s slave rcs

        ( CASAPATH="$BASEROOT $ARCH $SITE $HOST" ; \
          export CASAPATH ; \
          mktree -l -r -s )
     fi
  fi


#-----------------------------------------------------------------------------
# Rebuild all systems
#-----------------------------------------------------------------------------

  cd $AIPSROOT

  echo ""
  echo "inhale: Rebuild AIPS++ version $INCVERSN on all systems."
  echo "--------------------------------------------------------"

# List of hosts which will rebuild each architecture.
  INHOSTS=`getrc -i inhale.sneeze.hosts 2> /dev/null`
  DELTASLEEP=`getrc -i inhale.sneeze.sleep 2> /dev/null`
  if [ "$DELTASLEEP" = "" ]
  then
     DELTASLEEP=600
  fi
  SLEEPINV=$DELTASLEEP

# No need to sneeze anywhere else if we're a binary installation
  if [ "$BINARY" ]
  then
     INHOSTS=
  fi

# Spread our germs to all specified hosts.
  GOTSYNC=
  for INHOST in $INHOSTS
  do
#    Parse any architecture extension.
     EXTLIST=""
     case $INHOST in
     *:*)
        EXTLIST=`echo $INHOST | sed -e 's/[^:]*://'`
        INHOST=`echo $INHOST | sed -e 's/:.*//'`
        ;;
     esac

#    Synchronous rebuild on this host.
     if [ "$GOTSYNC" = "" -a "$INHOST" = "$HOST" ]
     then
        GOTSYNC=1
        INEXT="$EXTLIST"
        continue
     fi

#
# OK here is where we put the binary extraction possibly gunzip/tar xf -
#
#    Determine what command to use for remote sneeze.  Default is ssh.
     RCMD=`getrc -i inhale.sneeze.$INHOST.rcmd 2> /dev/null`
     [ "$RCMD" = "" ] && RCMD=ssh

     echo ""
     TMP="$INHOST"
     [ "$EXTLIST" != "" ] && TMP="$TMP ($EXTLIST)"
     echo "inhale: Initiating asynchronous rebuild on $TMP using $RCMD..."

#    Initiate the rebuild.
     if [ "$EXTLIST" != "" ]
     then
        EXTLIST="-e $EXTLIST"
        AIPSEXT=`echo "$EXTLIST" | sed -e 's/:.*//'`
     fi
     SNEEZE="sneeze $EXTLIST -l -m $MODE -s $SLEEPINV $TARGETS"
     echo $RCMD $INHOST -n $AIPSROOT/.rshexec $AIPSEXT \'$SNEEZE\'
     $RCMD $INHOST -n $AIPSROOT/.rshexec $AIPSEXT \'$SNEEZE\' &
     SLEEPINV=`expr $SLEEPINV + $DELTASLEEP`
  done

# Start the rebuild on this host.
  echo ""
  echo "inhale: `adate`"
  AIPSEXT=
  TMP=
  if [ "$INEXT" != "" ]
  then
     AIPSEXT=`echo $INEXT | sed -e 's/:.*//'`
     TMP=" ($INEXT)"
     INEXT="-e $INEXT"
  fi

# No need to sneeze anywhere else if we're a binary installation
  if [ "$BINARY" ]
  then
     echo "inhale: Skipping sneeze due to binary flag"
  else
     echo "inhale: Initiating synchronous rebuild$TMP..."
     (aips_ext=$AIPSEXT . $AIPSROOT/aipsinit.sh ; \
      sneeze $INEXT -l -m $MODE $TARGETS)
  fi

#
# Now we look to see if we're going to cvsup the docs or data
#
  if [ "$USECVSUP" ]
  then
     doit="yes"
     CVSUP="cvsup -g "

# Ensure that cvsup is installed here.

     for DIREX in `echo $PATH | sed -e 's/:/ /g'` ""
     do
       [ -f "$DIREX/cvsup" ] && break
     done

     if [ "$DIREX" = "" ]
     then
       echo ""
       echo "inhale: cvsup does not appear to be available (check your" \
            "PATH), abort!"
       doit="no"
     fi

     case $CVSUPGET in
       data)
         FETCHCVSUP="data"
       break
       ;;
       docs)
         FETCHCVSUP="docs"
       break
       ;;
       all)
         FETCHCVSUP="data docs"
       ;;
       *)
       doit="no"
       break
       ;;
     esac
     if [ $doit = "yes" ]
     then
	for fetchme in $FETCHCVSUP
        do
            SUPFILE=$AIPSROOT/$fetchme/supfile
            if [ -f $SUPFILE ]
	    then
	       echo "Supfile exists."
            else
	       if [ -d $AIPSROOT/$fetchme ]
	       then
		  echo "$fetchme directory exists"
	       else
		  mkdir $AIPSROOT/$fetchme
	       fi
	       echo "Creating supfile."
# First try to guess the release, default to daily
	       CVSUPVERS="daily"
               if [ "$BLESSED" != "" ]
               then
	           CVSUPVERS="stable"
               elif [ "$RELEASE" != "" ]
               then
	           CVSUPVERS="released"
	       else
	           echo $AIPSROOT | grep weekly
	           if [ $? -eq 0 ] 
	           then 
                      CVSUPVERS='weekly'
	           fi
               fi
	       if [ $fetchme = 'data' ]
	       then
	           CVSUPVERS="all"
	       fi
	       echo "*default host=aips2.nrao.edu compress" > $SUPFILE
#
#  data is different from docs so the base is different
#
               if [ $fetchme != "data" ]
               then
	          echo "*default base=$AIPSROOT" >> $SUPFILE
               else
	          echo "*default base=$AIPSROOT/$fetchme" >> $SUPFILE
               fi
	       echo "*default release=$CVSUPVERS" >> $SUPFILE
	       echo "*default delete use-rel-suffix" >> $SUPFILE
	       echo "$fetchme" >> $SUPFILE

            fi
            $CVSUP $SUPFILE
	done
     fi
  fi

#-----------------------------------------------------------------------------
# Wind up.
#-----------------------------------------------------------------------------
  if [ "$MODE" != incremental ]
  then
     echo ""
     if [ -f $AIPSROOT/.rhosts ]
     then
        echo "inhale: Remote $MGRACCNT:"
        cat $AIPSROOT/.rhosts
     else
        echo "inhale: No remote $MGRACCNT."
     fi
  fi

  echo ""
  echo "inhale: Execution terminated at"
  echo "inhale: `adate`"
  echo "inhale: `adate -l`"


# Resubmit ourselves if necessary.
  [ "$MODE" = base -a "$NEWMINOR" != 000 ] && exec inhale $ARGS

  exit 0
