#!/bin/sh
#-----------------------------------------------------------------------------
# exhale: Update the AIPS++ source distribution files
#-----------------------------------------------------------------------------
#
#   Copyright (C) 1992-1997,1999,2000,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: aips2-request@nrao.edu.
#          Postal address: AIPS++ Project Office
#                          National Radio Astronomy Observatory
#                          520 Edgemont Road
#                          Charlottesville, VA 22903-2475 USA
#
#-----------------------------------------------------------------------------
# Usage: exhale [-e] [-l]
#-----------------------------------------------------------------------------
# exhale generates updates for the AIPS++ code distribution system.  It
# deposits compressed tar files in the AIPS++ master ftp directory and these
# may be fetched and installed in slave installations by a complementary
# utility known as 'inhale'.  exhale is only for use on the AIPS++ master
# (on aips2.nrao.edu) where it is normally invoked twice a day as a cron job.
#
# Options:
#   -e     Expire mode; "outdates" old RCS revisions.  Only useful when
#          exhale is creating a new base release; ignored otherwise.
#
#   -l     Latchkey mode; the update produced will be invisible to
#          'inhale' unless it is also invoked with the "-l" option.
#          (This mode is now pretty much obsolete.)
#
#   -F     Force mode; turn off all sanity checks for things like
#          running under the correct account, the proper site, etc.
#          DO NOT USE!  This option is only intended for use as a
#          debugging tool to maintain exhale itself.  DO NOT USE!
#          Also suppresses all e-mail output.
#          (This option is not listed in any usage instructions.)
#
#   -G     GNU tar mode; use options compatible with GNU tar.
#          Also only intended for use as a debugging tool.
#          (This option is not listed in any usage instructions.)
#
# The $MSTRFTPD/VERSION file is used as a timestamp file for the update.  It
# also contains the major and minor version numbers of the most recent update.
#
# Latchkey updates are used to restrict the AIPS++ distribution temporarily,
# for example, when the AIPS++ sources are undergoing significant structural
# changes which may take several days to complete.  Instead of switching
# 'exhale' off during this period, it may continue to be run in latchkey mode.
# The latchkey mechanism hides updates from general view, but slave
# installations which do want to track the changes may do so by specifying the
# "-l" latchkey option to 'inhale'.  Latchkey mode is terminated as soon as
# 'exhale' is invoked without the "-l" option, even if there are no files to
# be updated.
#
# The latchkey mechanism works by recording a version and timestamp on the
# second line of the $MSTRFTPD/VERSION file.  Normally 'inhale' obtains the
# current version number from the first line, but if invoked with the "-l"
# option it reads the last line instead.
#
# Status return values correspond to the four phases of the operation
#    0:  success
#    1:  initialization error
#    2:  error creating a new base release
#    3:  error creating incremental update
#    4:  error creating cumulative update
#    5:  error creating public release
#    6:  installation error
#
# Notes:
#    1) To begin a new base release, manually increment the major release
#       number and set the minor release number to "-" in $MSTRFTPD/VERSION.
#       This will also generate a new release of the AIPS++ sources for public
#       distribution via the code_ftp directory.
#
#    2) The AIPSMSTR and MSTRFTPD directory hierarchies must reside in the
#       same unix filesystem.
#
#    3) In principle, newly created but empty directories should be
#       propagated.  However, this is difficult to implement because it
#       requires finding all recently modified directories which are empty,
#       and there's no simple test for an empty directory.  Adding a non-
#       empty directory to the 'tar' include list would propagate everything
#       in it, and of course, 'tar' automatically propagates newly created
#       directories which contain newly created files.
#
#    4) Known bug: exhale will break if GNU tar (gtar) is the system's
#       default tar.  Using the -G option to exhale will fix this.
#
#    5) Need to document "blessing" mode.
#
# Original: 1992/04/06 by Mark Calabretta, ATNF
# $Id$
#=============================================================================
# Initialize
#-----------------------------------------------------------------------------
# Guard against being overwritten.
  case $0 in
  *-)
     ARGS=$*
     ;;
  *)
     cp $0 $0-
     exec $0- $*
     ;;
  esac

# Identify ourselves.
  HOST=`uname -n`
  LOGNAME=${LOGNAME-$USER}

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

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

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

# 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 "exhale: The AIPS++ root directory does not exist or is"
     echo "        not accessible: $AIPSROOT"
     exit 1
  fi

# Parse command options.
  EXPIREOUT=""
  LATCHKEY=""
  INSANE=""
  TAROPTS=-I
  while [ "$#" -gt 0 ]
  do
     case $1 in
     -e)
        EXPIREOUT=1
        echo ""
        echo "exhale: Expiring outdated RCS information."
        ;;
     -l)
        LATCHKEY=1
        echo ""
        echo "exhale: WARNING - using latchkey mode."
        ;;
     -F)
        INSANE=1
        echo ""
        echo "exhale: WARNING - no sanity checking!"
        ;;
     -G)
        TAROPTS=-T
        echo ""
        echo "exhale: Using options compatible with GNU tar."
        ;;
     *)
        exec 1>&2
        echo ""
        echo "Usage: exhale [-e] [-l]"
        exit 1
        ;;
     esac

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

     shift
  done

# Check that we come from Socorro.
  SITE=`echo $CASAPATH | awk '{ print $3 }'`
  if [ "$SITE" != socorro -a "$INSANE" = "" ]
  then
     exec 1>&2
     echo ""
     echo "exhale: This utility must only be run on the master machine" \
          "at Socorro, abort!"
     exit 1
  fi

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

# If running in INSANE (debug) mode, use $LOGNAME as $ADMACCNT.
  [ "$ADMACCNT" != "$LOGNAME" -a "$INSANE" != "" ] && ADMACCNT="$LOGNAME"

# Set file protection mask.
  umask 022


# Define major AIPS++ directories.
  AIPSMSTR="$AIPSROOT/master"
  MSTRETCD="$AIPSMSTR/etc"
  AIPSARKV="$AIPSROOT/archive"
  MSTRFTPD="$AIPSROOT/pub/master"
  CODEFTPD="$AIPSROOT/pub/code"
  IMPTFTPD="$AIPSROOT/pub/import"

# Ensure that the master source code management utilities are up-to-date.
  echo ""
  echo "exhale: Updating the master source code management utilities..."
  gmake -C $MSTRETCD allsys
  PRGGROUP=aips2prg
  chgrp $PRGGROUP $MSTRETCD
  chmod ug=rwx,o=rx,g+s $MSTRETCD
  chgrp $PRGGROUP $MSTRETCD/*_master
  chmod u=rwx,go=rx,u+s $MSTRETCD/*_master

# Delete any RCS semaphore files older than a day.
  find $AIPSMSTR -name ",*," -mtime +0 -exec rm -f {} \;

# Define the list of code areas.
# Technically, trial should not be among these, but it's necessary.
  AREAS="install aips dish synthesis vlbi contrib doc trial display trialdisplay"
  CONSORTIA="atnf bima hia nfra nral nrao tifr jive npoi"
  AREAS="$AREAS $CONSORTIA"

# Check accessibility of the master ftp area.
  if [ ! -d "$MSTRFTPD" ]
  then
     exec 1>&2
     echo ""
     echo "exhale: The master ftp directory does not exist or is"
     echo "        not accessible: $MSTRFTPD"
     exit 1
  fi

# Check the previous VERSION file.
  if [ ! -f $MSTRFTPD/VERSION ]
  then
     exec 1>&2
     echo ""
     echo "exhale: No VERSION file in $MSTRFTPD, abort!"
     exit 1
  fi

# Find the previous version.
  OLDVERSN=`sed -n '$p' $MSTRFTPD/VERSION | awk '{ print $1 }'`
  OLDMAJOR=`echo $OLDVERSN | awk -F. '{ print $1 }'`
  OLDMINOR=`echo $OLDVERSN | awk -F. '{ print $2 }'`

# New major version?
  if [ "$OLDMINOR" = - ]
  then
     NEWMAJOR=$OLDMAJOR
     OLDMAJOR=`expr $OLDMAJOR + 99 | sed -e 's/^1//'`
     NEWMINOR=000
     MODE=base
  else
     NEWMAJOR=$OLDMAJOR
     NEWMINOR=`expr $OLDMINOR + 1001 | sed -e 's/^1//'`
     MODE=incremental
  fi

# Create the master ftp work area.
  MSTRTMPD=$MSTRFTPD/tmp
  if [ -d "$MSTRTMPD" ]
  then
     exec 1>&2
     echo ""
     echo "exhale: Directory $MSTRTMPD already exists, abort!"
     exit 1
  fi

  mkdir $MSTRTMPD
  if [ "$?" != 0 ]
  then
     exec 1>&2
     echo ""
     echo "exhale: Couldn't create $MSTRTMPD, abort!"
     exit 1
  fi
  cd $MSTRTMPD

# Interrupt processing.
  TRAPRM="$MSTRTMPD"
  trap 'echo "" ; \
        echo "exhale: Cleaning up..." ; \
        cd $AIPSROOT ; \
        echo rm -rf $TRAPRM ; \
        rm -rf $TRAPRM ; \
        exit' 0 1 2 3 15


# Create the new version files.
  MAJMIN="$NEWMAJOR.$NEWMINOR"
  NEWVERSN="$MAJMIN.00"
  echo "$NEWVERSN `adate`" > $MSTRTMPD/NEWVERSN
  if [ "$LATCHKEY" = "" ]
  then
     sed -n -e '$p' $MSTRFTPD/VERSION > $MSTRTMPD/OLDVERSN
     cp -p $MSTRTMPD/NEWVERSN $MSTRTMPD/FTPVERSN
  else
     cp $MSTRFTPD/VERSION $MSTRTMPD/OLDVERSN
     sed -n -e 1p $MSTRFTPD/VERSION | \
         cat - $MSTRTMPD/NEWVERSN > $MSTRTMPD/FTPVERSN
  fi
  chmod 444 $MSTRTMPD/???VERSN

# Disable checkins, checkouts, deletions, and renames.
  echo "exhale: Execution on $HOST by $LOGNAME at" > $MSTRTMPD/ident
  echo "exhale: `adate`"    >> $MSTRTMPD/ident
  echo "exhale: `adate -l`" >> $MSTRTMPD/ident
  echo "" >> $MSTRTMPD/ident

  for j in ai am amv ao ax
  do
     if [ ! -f "$MSTRETCD/${j}_disable" ]
     then
        TRAPRM="$TRAPRM $MSTRETCD/${j}_disable"
        cp $MSTRTMPD/ident $MSTRETCD/${j}_disable
     fi
  done

  rm -f $MSTRTMPD/ident

# Regenerate the pathname cache.
  cd $AIPSMSTR
  find * \( -type d -exec test -f {}/.oc \; -prune \) -o \
         \( -name '*.cc,v' -o \
            -name '*.h,v'  -o \
            -name '*.l,v'  -o \
            -name '*.y,v' \) -print | \
     sed -e '{s/\..*,v//;/.*\/$/d;}' | \
     sort -u | \
     gzip > $MSTRETCD/av_cache.gz
  chmod 644 $MSTRETCD/av_cache.gz
  rm -f $MSTRETCD/av_cache-*.gz


# Produce an incremental change log.
# First get and clear the AIPS++ changelog.
  cd $AIPSROOT/code
  co -l -q -p CHANGELOG.LAST > $MSTRTMPD/alog.log
  rm -f CHANGELOG.LAST
  touch CHANGELOG.LAST
  ci -q -m"cleared" CHANGELOG.LAST
  if [ -s $MSTRTMPD/alog.log ]
  then
     echo "" >> $MSTRTMPD/alog.log
     echo "" >> $MSTRTMPD/alog.log
     echo "RCS change log" >> $MSTRTMPD/alog.log
     echo "==============" >> $MSTRTMPD/alog.log
     echo "" >> $MSTRTMPD/alog.log
  fi

# Append the RCS change log.
  cd $MSTRTMPD
  sed -n -e '$s/^[^ ]* //p' $MSTRFTPD/VERSION > $MSTRTMPD/alog.time
  alog --file=$MSTRTMPD/alog.time --master --noheader >> $MSTRTMPD/alog.log
  if [ -s $MSTRTMPD/alog.log ]
  then
     echo ""
     echo ""
     echo "exhale: $MAJMIN change log:"
     echo ""
     cat $MSTRTMPD/alog.log
     echo ""

     [ "$INSANE" = "" ] && cat $MSTRTMPD/alog.log | \
        mail -s "$MAJMIN change log" aips2-changes@nrao.edu
  fi

  rm -f $MSTRTMPD/alog.log $MSTRTMPD/alog.time

# master repository bookkeeping
  cd $AIPSMSTR
  rm -f VERSION
  [ -f VERSION,v ] && co -q -l -p VERSION > /dev/null
  cp -p $MSTRTMPD/NEWVERSN VERSION
  [ -f VERSION,v ] && ci -q -mupdated VERSION
  cp -p $MSTRTMPD/NEWVERSN VERSION

# Exclude the master code management utilities from the tar file.
  cd $AIPSROOT
  echo "master/etc"     >  $MSTRTMPD/master.excl
  echo "master/LOGFILE" >> $MSTRTMPD/master.excl


#-----------------------------------------------------------------------------
# Create the base release.
#-----------------------------------------------------------------------------
# Produce a tar file containing the base release.
  if [ "$MODE" = base ]
  then
     echo ""
     echo "exhale: Create new base release, version $NEWVERSN."
     echo "---------------------------------------------------"

#    New base release; exclude RCS semaphore files and rescinded files.
     echo "master" > $MSTRTMPD/master.incl
     find master -type f -name ",*," -print >> $MSTRTMPD/master.excl
     find master -name ".*" -print >> $MSTRTMPD/master.excl

     TEMPMSTR="$MSTRTMPD/master"
     TEMPARKV="$MSTRTMPD/archive"

#    Copy the master.
     echo ""
     echo "exhale: Making a working copy of $AIPSMSTR..."

     cd $AIPSROOT
     tar cf - master | (cd $MSTRTMPD && tar pxf -)
     if [ "$?" != 0 ]
     then
        exec 1>&2
        echo ""
        echo "exhale: Failed to copy the master RCS repository."
        exit 2
     fi

#    Copy the existing archive.
     echo ""
     echo "exhale: Copying the existing archive..."
     cd $AIPSROOT
     if [ -d archive ]
     then
        tar cf - archive | (cd $MSTRTMPD && tar pxf -)
        if [ "$?" != 0 ]
        then
           exec 1>&2
           echo ""
           echo "exhale: Failed to copy the archive RCS repository, abort!"
           exit 2
        fi
     else
        mkdir $TEMPARKV
     fi

#    Apply ax_master to rescind or rename archive files and directories.
     echo ""
     echo "exhale: Rescind or rename archive files and directories..."
     ( CASAPATH="$MSTRTMPD"
       export CASAPATH
       ax_master -archive -c -s )
     if [ $? != 0 ]
     then
        exec 1>&2
        echo ""
        echo "exhale: Failed to rescind or rename archive files and" \
             "directories, abort!"
        exit 2
     fi

#    Create any new directories.
     echo ""
     echo "exhale: Creating new archive directories..."
     cd $MSTRTMPD
     find master -type d -print |
     {
        exec 3<&0 0</dev/null

        while read DIR 0<&3
        do
           DIR=`echo $DIR | sed -e 's#^master#archive#'`

#          Create the directory.
           if [ ! -d "$DIR" ]
           then
              if `mkdir $DIR`
              then
                 echo "exhale: Created directory $DIR"
              else
                 echo "exhale: Failed to create directory $DIR, abort!" 1>&2
                 exit 2
              fi
           fi
        done
     } || exit $?


#    Clean up the master and update the archive.
     echo ""
     echo "exhale: Clean up the master and update the archive."
     echo "---------------------------------------------------"

     echo ""
     echo "exhale: `adate -l`"
     cd $MSTRTMPD

#    Outdate intermediate revisions of the antepenultimate release.
     if [ "$NEWMAJOR" -gt 2 -a "$EXPIREOUT" != "" ]
     then
        OUTMAJOR=`expr $NEWMAJOR + 98 | sed -e 's/^1//'`
        OUTDATE=":$OUTMAJOR.999"

#       Delete rescinded files which are too old.
        echo ""
        echo "exhale: Deleting rescinded files for version $OUTMAJOR..."
        find master -name ".$OUTMAJOR.???_*" -print -exec rm -rf {} \;
     else
        OUTDATE=""
     fi

#    Assign symbolic names for the new RCS release.
     echo ""
     echo "exhale: Outdating old revisions, incrementing the RCS release"
     echo "        number, and updating the archive..."

     find master \( -name ".*,v" -o -name "*,v" \) -print |
     {
        exec 3<&0 0</dev/null

        while read RCSFILE 0<&3
        do
           echo ""
           [ "$OUTDATE" = "" ] && echo $RCSFILE

#          Is it locked?
           if [ "`rlog -L -R $RCSFILE`" = "$RCSFILE" ]
           then
#             Find out who has it locked.
              LOCKER=`sed -n -e '/^locks/,/;$/p' $RCSFILE | \
                         sed -n -e '2s/	\([^:]*\).*/\1/p'`

#             Transfer the lock to our name.
              cp -p $RCSFILE rcstmp
              chmod u+w $RCSFILE
              sed -e '/^locks/,/;$/s/'$LOCKER/$ADMACCNT/ rcstmp > $RCSFILE
              chmod u-w $RCSFILE
              rm -f rcstmp

#             Check it out.
              co -q $RCSFILE
              if [ "$?" != 0 ]
              then
                 exec 1>&2
                 echo ""
                 echo "exhale: Failed to check out $RCSFILE."
                 exit 2
              fi
           else
              LOCKER=""

#             Check it out with lock.
              co -l -q $RCSFILE
              if [ "$?" != 0 ]
              then
                 exec 1>&2
                 echo ""
                 echo "exhale: Failed to check out $RCSFILE."
                 exit 2
              fi
           fi

#          Clean up the RCS file.
           if [ "$OUTDATE" != "" ]
           then
#             Delete defunct symbolic revision names.
              cp -p $RCSFILE rcstmp
              chmod u+w $RCSFILE
              sed -e '/^symbols/,/;$/{/^	v..-000-00/s/;*$/;/;
                      /^	v'$OUTMAJOR'-/d;}' rcstmp > $RCSFILE
              chmod u-w $RCSFILE
              rm -f rcstmp

#             Outdate old revisions.
              rcs -o"$OUTDATE" $RCSFILE 2>&1 | \
                 grep -v "rcs error: branch number [0-9]* too low"
           fi

#          Check it back in.
           case $RCSFILE in
           */.*,v)
              ci -q $RCSFILE
              STATUS="$?"
              ;;
           *)
#             Assign new release number and symbolic revision.
              ci -f -q -m"exhale: Base release $NEWVERSN" \
                 -N"v$NEWMAJOR-000-00" -r"$NEWMAJOR.0" $RCSFILE
              STATUS="$?"
              ;;
           esac

           if [ "$STATUS" != 0 ]
           then
              exec 1>&2
              echo ""
              echo "exhale: Failed to check in $RCSFILE."
              exit 2
           fi

#          Replace the archive with the copy locked by aips2adm.
           RCSARKV=`echo $RCSFILE | sed -e "s#master/#archive/#"`
           if [ -f "$RCSARKV" ]
           then
#             Merge the RCS version files.
              rcscat $RCSFILE $RCSARKV > rcstmp
              if [ $? != 0 ]
              then
                 exec 1>&2
                 echo ""
                 rm -f rcstmp
                 echo "exhale: Failed to update $RCSARKV, abort!"
                 exit 2
              fi

              chmod u+w $RCSARKV
              cat rcstmp > $RCSARKV
              chmod u-w $RCSARKV

              rm -f rcstmp
           else
              cp $RCSFILE $RCSARKV
           fi

#          Lock the archive file.
           rcs -l $RCSARKV

           if [ "$LOCKER" != "" ]
           then
#             Transfer the lock back to its original owner.
              rcs -l $RCSFILE
              cp -p $RCSFILE rcstmp
              chmod u+w $RCSFILE
              sed -e '/^locks/,/;$/s/'$ADMACCNT/$LOCKER/ rcstmp > $RCSFILE
              chmod u-w $RCSFILE
              rm -f rcstmp
              echo "exhale: Lock transferred back to $LOCKER."
           fi
        done
     } || exit $?

#    Verify the master.
     xrcs -q $TEMPMSTR
     if [ "$?" != 0 ]
     then
        echo "exhale: Working copy of master not verified, abort!" 1>&2
        exit 2
     fi

#    Verify the archive.
     xrcs -q $TEMPARKV
     if [ "$?" != 0 ]
     then
        echo "exhale: Working copy of archive not verified, abort!" 1>&2
        exit 2
     fi

#    Recreate the version files so that they're newer than the RCS files.
     rm -f $MSTRTMPD/???VERSN
     echo "$NEWVERSN `adate`" > $MSTRTMPD/NEWVERSN
     if [ "$LATCHKEY" = "" ]
     then
        sed -n -e '$p' $MSTRFTPD/VERSION > $MSTRTMPD/OLDVERSN
        cp -p $MSTRTMPD/NEWVERSN $MSTRTMPD/FTPVERSN
     else
        cp $MSTRFTPD/VERSION $MSTRTMPD/OLDVERSN
        sed -n -e 1p $MSTRFTPD/VERSION | \
            cat - $MSTRTMPD/NEWVERSN > $MSTRTMPD/FTPVERSN
     fi
     chmod 444 $MSTRTMPD/???VERSN

#    Install the new VERSION file in TEMPMSTR and TEMPARKV.
     rm -f $TEMPMSTR/VERSION $TEMPARKV/VERSION
     cp -p $MSTRTMPD/NEWVERSN $TEMPMSTR/VERSION
     cp -p $MSTRTMPD/NEWVERSN $TEMPARKV/VERSION

#    Report the sizes of the archive and master repositories.
     echo ""
     echo "exhale: Space occupied by the archive and master (kbyte):"
     du -s archive master

     echo ""
     echo "exhale: `adate -l`"

#    Create the tar file.
     echo ""
     echo "exhale: Base release files for version $NEWVERSN:"

     cd $MSTRTMPD
     tar cvfX $MSTRTMPD/master-$MAJMIN.tar $MSTRTMPD/master.excl \
        $TAROPTS $MSTRTMPD/master.incl
     if [ "$?" != 0 ]
     then
        exec 1>&2
        echo ""
        echo "exhale: Failed to create the base release tar file."
        exit 2
     fi
  fi


#-----------------------------------------------------------------------------
# Create the incremental update.
#-----------------------------------------------------------------------------
  if [ "$MODE" = incremental ]
  then
#    Find all master files modified since the last incremental update.
     find master \( -type f -o -type l \) -name "*,v" \
        -newer $MSTRFTPD/VERSION -print | \
        sed -e '\#^master/etc/#d' \
            -e '\#/\.[0-9][0-9]\.[0-9][0-9][0-9]_.*/#d' > \
        $MSTRTMPD/master.newer

#    Was anything modified?
     if [ -s "$MSTRTMPD/master.newer" ]
     then
#       Add the master VERSION file.
        echo "master/VERSION" > $MSTRTMPD/master.incl
        sort $MSTRTMPD/master.newer >> $MSTRTMPD/master.incl
     else
        echo ""
        echo "exhale: No files have been modified since the last update."

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

        [ -f VERSION ] && mv -f VERSION VERSION_
        mv -f $MSTRTMPD/OLDVERSN $MSTRFTPD/VERSION

        chmod 444 VERSION LOGFILE
        rm -f VERSION_ LOGFILE_

        rm -f $AIPSMSTR/LOGFILE
        cp -p LOGFILE $AIPSMSTR

        cd $AIPSROOT
        rm -rf $TRAPRM
        trap 0

        exit 0
     fi

#    Create the tar file.
     echo ""
     echo "exhale: Incremental update files for version $NEWVERSN."
     echo "-------------------------------------------------------"

     cd $AIPSROOT
     tar cvfX $MSTRTMPD/master-$MAJMIN.tar $MSTRTMPD/master.excl \
        $TAROPTS $MSTRTMPD/master.incl
     if [ "$?" != 0 ]
     then
        exec 1>&2
        echo ""
        echo "exhale: Failed to create the incremental update tar file."
        exit 3
     fi
  fi


#-----------------------------------------------------------------------------
# Bookkeeping jobs common to base and incremental updates.
#-----------------------------------------------------------------------------
# Prepare the code distribution manifest.
  echo ""
  echo "exhale: Preparing the manifest..."
  cd $MSTRTMPD

  tar tf master-$MAJMIN.tar > tarlist
  if [ "$?" != 0 ]
  then
     exec 1>&2
     echo ""
     echo "exhale: Failed to create the code distribution manifest."
     exit 3
  fi

# Reformat it.
  cp NEWVERSN MANIFEST
  chmod 644 MANIFEST
  echo "-------------------------------------"  >> MANIFEST
  sort tarlist | sed -e "s#^master/#$MAJMIN  #" >> MANIFEST

  if [ -f "$MSTRFTPD/MANIFEST" -a "$MODE" != base ]
  then
#    Append the old manifest.
     echo "" >> MANIFEST
     mv MANIFEST MANIFEST_
     cat MANIFEST_ $MSTRFTPD/MANIFEST > MANIFEST
  fi

# Compress the tar file.
  echo ""
  echo "exhale: Compressing the $MODE tar file..."
  gzip --best --verbose master-$MAJMIN.tar
  if [ "$?" != 0 ]
  then
     exec 1>&2
     echo ""
     echo "exhale: Couldn't compress the tar file."
     exit 3
  fi

  chmod 444 master-$MAJMIN.tar.gz


#-----------------------------------------------------------------------------
# Create the cumulative update.
#-----------------------------------------------------------------------------
# Find all master files modified since the last base release.
  if [ "$MODE" = incremental ]
  then
     ALLVERS="$MAJMIN.ALL"
     cd $AIPSROOT
     find master \( -type f -o -type l \) -name "*,v" \
        -newer $MSTRFTPD/master-$NEWMAJOR.000.tar.gz  -print | \
        sed -e '\#^master/etc/#d' \
            -e '\#/\.[0-9][0-9]\.[0-9][0-9][0-9]_.*/#d' > \
        $MSTRTMPD/master.newer

#    Was anything modified?
     if [ ! -s "$MSTRTMPD/master.newer" ]
     then
        exec 1>&2
        echo ""
        echo "exhale: Apparently no files were modified since the last"
        echo "        base release, although some were since the last"
        echo "        incremental release!  Check the creation dates of"
        echo "           $MSTRFTPD/VERSION"
        echo "           $MSTRFTPD/master-$NEWMAJOR.000.tar.gz"

        exit 4
     fi

#    Add the master VERSION file.
     echo "master/VERSION" > $MSTRTMPD/master.incl
     sort $MSTRTMPD/master.newer >> $MSTRTMPD/master.incl

#    Produce a tar file containing the modified files.
     echo ""
     echo "exhale: Cumulative update files for version $NEWVERSN."
     echo "------------------------------------------------------"
     tar cvf $MSTRTMPD/master-$ALLVERS.tar $TAROPTS $MSTRTMPD/master.incl
     if [ "$?" != 0 ]
     then
        exec 1>&2
        echo ""
        echo "exhale: Failed to create the cumulative update tar file."
        exit 4
     fi

#    Compress it.
     cd $MSTRTMPD
     echo ""
     echo "exhale: Compressing the cumulative tar file..."
     gzip --best --verbose master-$ALLVERS.tar
     if [ "$?" != 0 ]
     then
        exec 1>&2
        echo ""
        echo "exhale: Couldn't compress the cumulative update tar file."
        exit 4
     fi

     chmod 444 master-$ALLVERS.tar.gz
  fi


#-----------------------------------------------------------------------------
# Create a new public release.
#-----------------------------------------------------------------------------
  if [ "$MODE" = base ]
  then
     echo ""
     echo "exhale: `adate -l`"

     echo ""
     echo "exhale: Create the public release for version $NEWVERSN."
     echo "--------------------------------------------------------"

#    Path to the temporary system.
     MSTRPATH="$MSTRTMPD `echo $CASAPATH | awk '{ print $2, $3, $4 }'`"

#    Create a temporary code tree.
     echo "exhale: Creating a working code tree..."
     cd $MSTRTMPD
     TEMPCODE=$MSTRTMPD/code
     (CASAPATH="$MSTRPATH" ; export CASAPATH ; mktree -master -s)
     rm -rf $TEMPCODE/etc

#    Link to the master RCS repository for the checkout.
     ln -s $TEMPMSTR rcs

#    Create a rudimentary system area for "makedefs".
     ARCH=`echo $CASAPATH | awk '{ print $2 }'`
     mkdir $ARCH
     co -p rcs/install/makedefs > $ARCH/makedefs

#    Checkout everything.
     echo ""
     echo "exhale: Checking out all sources..."
     cd $TEMPCODE
     gmake CASAPATH="$MSTRPATH" AIPSRCS=$TEMPMSTR CONSORTIA="$CONSORTIA" \
        NODEP=1 chkout

#    Check the accessibility of the code ftp area.
     if [ ! -d "$CODEFTPD" ]
     then
        mkdir $CODEFTPD
        if [ "$?" != 0 ]
        then
           exec 1>&2
           echo ""
           echo "exhale: The code ftp directory does not exist and"
           echo "        could not be created: $CODEFTPD"
           exit 5
        fi
     fi

#    Install the configure utility.
     rm -f $CODEFTPD/configure

     cd $IMPTFTPD
     GZIPS=`echo gzip-*.tar`
     GMAKE=`echo make-*.tar.gz`
     BISON=`echo bison-*.tar.gz`
     FLEX=`echo flex-*.tar.gz`
     PERL=`echo perl-*.tar.gz`

     cat $TEMPCODE/install/configure | \
     sed -e "s#__GZIP#$GZIPS#" \
         -e "s#__GMAKE#$GMAKE#" \
         -e "s#__BISON#$BISON#" \
         -e "s#__FLEX#$FLEX#" \
         -e "s#__PERL#$PERL#" > $CODEFTPD/configure
     chmod 444 $CODEFTPD/configure

#    Create a temporary work area.
     CODETMPD=$CODEFTPD/tmp
     TRAPRM="$TRAPRM $CODETMPD"

     mkdir $CODETMPD
     if [ "$?" != 0 ]
     then
        exec 1>&2
        echo ""
        echo "exhale: Couldn't create $CODETMPD, abort!"
        exit 5
     fi

     for AREA in $AREAS
     do
#       Construct a list of RCS symlinks to exclude.
        cd $TEMPCODE
        find $AREA -name RCS -print > $CODETMPD/$AREA.excl

#       The install distribution file includes the top level makefile.
        if [ "$AREA" = install ]
        then
           AREALIST="$AREA makefile"
        else
           AREALIST="$AREA"
        fi

#       Produce a new tar file.
        echo ""
        echo "exhale: Creating the ftp distribution tar file for $AREA..."

        cd $TEMPCODE
        tar cvfX $CODETMPD/$AREA-$MAJMIN.tar $CODETMPD/$AREA.excl \
           $AREALIST
        if [ "$?" != 0 ]
        then
           exec 1>&2
           echo ""
           echo "exhale: Failed to create the $AREA-$MAJMIN tar file."
           exit 5
        fi

#       Compress it.
        cd $CODETMPD
        gzip --best --verbose $AREA-$MAJMIN.tar
        if [ "$?" != 0 ]
        then
           exec 1>&2
           echo ""
           echo "exhale: Couldn't compress the $AREA-$MAJMIN tar file."
           exit 5
        fi

        chmod 444 $AREA-$MAJMIN.tar.gz
     done
  fi


#-----------------------------------------------------------------------------
# Install the updates.
#-----------------------------------------------------------------------------

  echo ""
  echo "exhale: Install distribution files for version $NEWVERSN."
  echo "---------------------------------------------------------"

# Looks OK so far, catch and kill all catchable interrupts.
  trap 'echo "exhale: Interrupt ignored."' 1 2 3 15

  echo ""
  echo "exhale: Interrupts disabled, do not SIGKILL."
  echo "exhale: `adate -l`"

  cd $MSTRFTPD

  if [ "$LATCHKEY" = "" ]
  then
#    New prayer: forget about any previous blessings.
     OLDBLESSED=`echo .blessed-master-*.tar.gz`
     echo ""
     echo "exhale: Removing old blessed versions:"

     for OLDBLESSING in $OLDBLESSED
     do
        echo "        $OLDBLESSING"
        rm -f $OLDBLESSING
     done

#    Count our blessings.
     if [ -f "BLESSED" ]
     then
        BLESSED=`cat BLESSED | sed 's/#.*//'| awk '{print $1}'`

        for BLESSING in $BLESSED
        do
#          Need to prevent attempting duplicate links here.
           [ -f "master-$BLESSING.tar.gz" ] && \
            echo "exhale: Blessing incremental $BLESSING" && \
            ln "master-$BLESSING.tar.gz" ".blessed-master-$BLESSING.tar.gz"
           [ -f "master-$BLESSING.ALL.tar.gz" ] && \
            echo "exhale: Blessing cumulative $BLESSING" && \
            ln "master-$BLESSING.ALL.tar.gz" ".blessed-master-$BLESSING.ALL.tar.gz"
        done
     fi

#    Delete incremental updates which are more than 30 days old
#    with only one link.
     find . -name tmp -prune -o -name "master-$NEWMAJOR.???.tar.gz" \
        ! -name master-$NEWMAJOR.000.tar.gz \
        -mtime +30 -links 1 -exec rm -f {} \;

#    Delete cumulative updates which are more than 7 days old
#    with only one link.
     find . -name tmp -prune -o -name "master-$NEWMAJOR.???.ALL.tar.gz" \
        -mtime +7 -links 1 -exec rm -f {} \;
  else
#    Delete the previous cumulative latchkey update only.
     SAVE=`sed -n '1s/\.00 .*//p' $MSTRTMPD/FTPVERSN`
     if [ "$NEWMAJOR.$OLDMINOR" != "$SAVE" ]
     then
        rm -f $MSTRFTPD/master-$NEWMAJOR.$OLDMINOR.ALL.tar.gz
     fi
  fi

# Move the new update files into the master ftp area.
  if mv -f $MSTRTMPD/master-$MAJMIN*.tar.gz $MSTRFTPD
  then
     echo ""
     echo "exhale: Installed the master update file(s)."
     gzip --list master-$MAJMIN*.tar.gz
  else
     exec 1>&2
     echo ""
     echo "exhale: Failed to install the master update file(s)."

     rm -f $MSTRFTPD/*-$MAJMIN*.tar.gz

     exit 6
  fi

  if [ "$MODE" = base ]
  then
#    Install the public release files.
     cd $CODEFTPD
     echo ""

     for AREA in $AREAS
     do
        if mv -f $CODETMPD/$AREA-$MAJMIN.tar.gz $CODEFTPD
        then
           echo "exhale: Installed the $AREA distribution file."
        else
           exec 1>&2
           echo ""
           echo "exhale: Failed to install the $AREA distribution file."

           rm -f $MSTRFTPD/*-$MAJMIN*.tar.gz
           rm -f $CODEFTPD/*-$MAJMIN.tar.gz

           exit 6
        fi
     done

     echo ""
     gzip --list *-$MAJMIN.tar.gz

#    Save the archive.
     [ -d "$AIPSARKV" ] && mv -f $AIPSARKV $AIPSARKV.$$
     if mv -f $TEMPARKV $AIPSARKV
     then
        echo ""
        echo "exhale: Installed the master archive in $AIPSARKV."
     else
        exec 1>&2
        echo ""
        echo "exhale: Failed to install the master archive in $AIPSARKV."

        rm -f $MSTRFTPD/*-$MAJMIN*.tar.gz
        rm -f $CODEFTPD/*-$MAJMIN.tar.gz
        rm -rf $AIPSARKV
        mv -f $AIPSARKV.$$ $AIPSARKV

        exit 6
     fi

#    Install the new master.
     mv -f $AIPSMSTR $AIPSMSTR.$$
     if mv -f $TEMPMSTR $AIPSMSTR
     then
        echo ""
        echo "exhale: Installed the new master in $AIPSMSTR."

        echo ""
        echo "exhale: Updating the master source code management utilities..."
        gmake -C $MSTRETCD allsys
        PRGGROUP=aips2prg
        chgrp $PRGGROUP $MSTRETCD
        chmod ug=rwx,o=rx,g+s $MSTRETCD
        chgrp $PRGGROUP $MSTRETCD/*_master
        chmod u=rwx,go=rx,u+s $MSTRETCD/*_master
     else
        exec 1>&2
        echo ""
        echo "exhale: Failed to install the new master in $AIPSMSTR."

#       Recover the old master.
        echo "exhale: Recovering the old master..."
        [ -d "$AIPSMSTR.abort" ] && rm -rf $AIPSMSTR.abort
        [ -d "$AIPSMSTR" ] && mv -f $AIPSMSTR $AIPSMSTR.abort
        mv -f $AIPSMSTR.$$ $AIPSMSTR

#       Recover the old archive.
        echo "exhale: Recovering the old archive..."
        [ -d "$AIPSARKV.abort" ] && rm -rf $AIPSARKV.abort
        [ -d "$AIPSARKV" ] && mv -f $AIPSARKV $AIPSARKV.abort
        mv -f $AIPSARKV.$$ $AIPSARKV

        rm -f $MSTRFTPD/*-$MAJMIN*.tar.gz
        rm -f $CODEFTPD/*-$MAJMIN.tar.gz

        exit 6
     fi
  fi


# Take care of the bookkeeping.
  cd $MSTRFTPD

# Produce a new checksum file.
  rm -f CHKSUM
  cksum .*binary* master-* > CHKSUM
  chmod 444 CHKSUM

# Update the version files.
  [ -f LOGFILE ] || touch LOGFILE
  mv -f LOGFILE LOGFILE_
  if [ "$LATCHKEY" = "" ]
  then
     echo "$NEWVERSN `adate`" | cat - LOGFILE_ > LOGFILE
  else
     echo "$NEWVERSN `adate`  (latchkey)" | cat - LOGFILE_ > LOGFILE
  fi

  [ -f VERSION ] && mv -f VERSION VERSION_
  mv -f $MSTRTMPD/FTPVERSN VERSION

  chmod 444 VERSION LOGFILE
  rm -f VERSION_ LOGFILE_

  if [ "$MODE" = base ]
  then
     rm -f $AIPSARKV/LOGFILE
     cp -p LOGFILE $AIPSARKV/LOGFILE

     rm -f $CODEFTPD/VERSION
     cp -p $MSTRTMPD/NEWVERSN $CODEFTPD/VERSION
  fi

# Update the code distribution manifest.
  if [ "$MODE" = base ]
  then
#    Preserve the old LOGFILE.
     rm -f "LOGFILE-$OLDMAJOR"
     cp LOGFILE "LOGFILE-$OLDMAJOR"

#    Preserve the old MANIFEST.
     if [ ! -f "MANIFEST-$OLDMAJOR" ]
     then
        mv MANIFEST "MANIFEST-$OLDMAJOR"
     elif [ -s "MANIFEST" ]
     then
        mv MANIFEST "MANIFEST-$OLDMAJOR.$$"
     fi
  fi

  rm -f MANIFEST
  mv -f $MSTRTMPD/MANIFEST .
  chmod 444 MANIFEST

# master repository bookkeeping
  cd $AIPSMSTR
  rm -f VERSION LOGFILE
  [ -f VERSION,v ] && co -q -l -p VERSION > /dev/null
  cp -p $MSTRTMPD/NEWVERSN VERSION
  [ -f VERSION,v ] && ci -q -mupdated VERSION
  cp -p $MSTRTMPD/NEWVERSN VERSION
  cp -p $MSTRFTPD/LOGFILE LOGFILE

# tag rcs files for this exhale version
  echo ""
  echo "exhale: tagging repository files..."
  echo "exhale: `adate`"
  atag  -T "ex$NEWMINOR" -T exhale .

# Clean up.
  cd $AIPSROOT
  rm -rf $TRAPRM
  rm -rf $AIPSARKV.$$ $AIPSMSTR.$$
  trap 0


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

# Local Variables:
# indent-tabs-mode: nil
# ksh-indent: 3
# ksh-group-offset: -3
# End:
