#!/bin/sh
#-----------------------------------------------------------------------------
# updatelib: Update an AIPS++ library
#-----------------------------------------------------------------------------
#
#   Copyright (C) 1992-1997,1999
#   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: updatelib [-f] package
#-----------------------------------------------------------------------------
# updatelib updates the AIPS++ object libraries associated with a particular
# package.  It is normally used only by AIPS++ makefiles.  It can process dual
# debug and optimized libraries concurrently with another invokation, possibly
# on another machine.
#
# Options:
#   -f     Force a ranlib and rebuild of the sharable objects even if no new
#          object modules are found.
#
# An "_f" appended to the package name, for example "aips_f", indicates that
# the FORTRAN libraries for the package are to be updated rather than the
# default C++ libraries.
#
# Status returns:
#    0:  success
#    1:  initialization error
#    2:  library update failed
#
# If any library update fails, none of the libraries will be updated.
#
# Original: 1992/04/03 by Mark Calabretta, ATNF
# $Id$
#=============================================================================
# Parse command input.
  FORCE=""
  PCKGLANG=""
  NEEDSVERSION=""
  JNISFXSHAR=""

  while [ "$#" -gt 0 ]
  do
     case $1 in
        -f)
           FORCE=1
           ;;
        -jni)
           if [ `uname -s` != "Linux" ]
           then
              JNISFXSHAR="jnilib"
           fi
           ;;
        -v)
           NEEDSVERSION="version.o"
           ;;
        *)
           PCKGLANG=$1
           ;;
     esac

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

     shift
  done

# Check the package name.
  if [ "$PCKGLANG" = "" ]
  then
     exec 1>&2
     echo "Usage: updatelib [-f] package"
     echo '       ...where "package" is the name of an AIPS++ package'
     echo '       ...such as "aips", "synthesis", etc.'
     exit 1
  fi

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

# Default file creation mask.
  umask 002

# Check for FORTRAN updates.
  case $PCKGLANG in
  *_c)
     LANGUAGE=C
     PACKAGE=`echo $PCKGLANG | sed -e 's/_c$//'`
     ;;
  *_f)
     LANGUAGE=FORTRAN
     PACKAGE=`echo $PCKGLANG | sed -e 's/_f$//'`
     ;;
  *)
     LANGUAGE=C++
     PACKAGE="$PCKGLANG"
     ;;
  esac

# Check that the package is valid.
  AIPSROOT=`echo $CASAPATH | awk '{ print $1 }'`
  if [ ! -d "$AIPSROOT/code/$PACKAGE" ]
  then
     echo "updatelib: $PACKAGE is not a recognized AIPS++ package." 1>&2
     exit 1
  fi

# Get the host architecture.
  ARCH=`echo $CASAPATH | awk '{ print $2 }'`

# Get the system area and library names.
  AIPSARCH=`echo $CASAPATH | awk '{ print $1 "/" $2 }'`
  TMPPCKGD="$AIPSARCH/tmp/$PCKGLANG"

# Construct an identifier string.
  HOST=`echo $CASAPATH | awk '{ print $4 }'`
  ID="$USER@$HOST"

# Load makedefs variables into the environment if necessary.
  echo "#$AR#$ARFLAGS#$RANLIB#$CXXAR#$CXXARDBG#$CXXAROPT#$UPDBATCH#$LD#" \
       "#$SFXSTAT#$SFXSHAR#$MKSO#F77LIBD#F77LIB#$XTRNLIBS_shared#$XTRNLIBS_rpath#" | grep '##' > /dev/null 2>&1
  if [ "$?" = 0 ]
  then
     VARS="AR ARFLAGS RANLIB CXXAR CXXARDBG CXXAROPT UPDBATCH LD LDSOPTS SFXSTAT SFXSHAR LIB$PACKAGE LINK$PACKAGE MKSO F77LIBD F77LIB XTRNLIBS_shared XTRNLIBS_rpath"
     eval `gmake -f $AIPSARCH/makedefs VARS="$VARS" eval_vars`
  fi

  # Handle the case for jni libraries as they require special suffix
  if [ "$JNISFXSHAR" = "jnilib" ]; then
     SFXSHAR=$JNISFXSHAR
  fi

  PCKGLIBR=lib$PCKGLANG.$SFXSTAT
  dARCH=`echo "$ARCH" | egrep "^(darwin|osx)"`
  if [ "$dARCH" ]; then
     XTRNPATH=""
  else
     if [ -n "$XTRNLIBS_rpath" ]; then
        XTRNPATH=$XTRNLIBS_rpath
     else
        XTRNPATH=-Wl,-rpath,/usr/lib:/lib
     fi
  fi

# Ensure the package temporary area exists.
  if [ ! -d "$TMPPCKGD" ]
  then
     mkdir $TMPPCKGD
     chmod 775 $TMPPCKGD
     chmod g+s $TMPPCKGD
  fi
  cd $TMPPCKGD

# Initialize the abort handling.
  LIBS=""
  LOCKS=""
  PROCESS="$TMPPCKGD/updatelib.process.$ID"
  PROCEED="$TMPPCKGD/updatelib.proceed"
  trap 'rm -f $LIBS $LOCKS $PROCESS $PROCEED' 0
  trap 'exec 1>&2 ; \
        echo "" ; \
        echo "Cleaning up..." ; \
        exit 1' 1 2 3 15

# Declare our intentions.
  set `echo updatelib.process.*`
  if [ "$1" = "updatelib.process.*" ]
  then
#    We're first, create the "all-is-well" semaphore file.
     touch $PROCESS $PROCEED
  else
#    Exit immediately if an abort has been signalled.
     [ -f "$PROCEED" ] || exit 2
     ln $1 $PROCESS
  fi

# Loop for the debug and optimized libraries.
  for LEVEL in dbg opt
  do
#    How to archive object modules.
     case $LANGUAGE in
     C++)
        case $LEVEL in
        dbg)
           ARCHIVE="$CXXAR $CXXARDBG"
           ;;
        opt)
           ARCHIVE="$CXXAR $CXXAROPT"
           ;;
        esac
        ;;
     *)
        ARCHIVE="$AR $ARFLAGS"
        ;;
     esac

     case $LEVEL in
     dbg)
        ARCHLIBD=$AIPSARCH/libdbg
        PCKGTMPD=$AIPSARCH/tmp/$PCKGLANG/dbg
        ;;
     opt)
        ARCHLIBD=$AIPSARCH/lib
        PCKGTMPD=$AIPSARCH/tmp/$PCKGLANG/opt
        ;;
     esac

#    Move into the work area.
     if [ ! -d "$PCKGTMPD" ]
     then
        [ "$FORCE" = "" ] && continue
        mkdir $PCKGTMPD
        chmod 775 $PCKGTMPD
        chmod g+s $PCKGTMPD
     fi
     cd $PCKGTMPD

#    Are there any modules or a library to update?
     MODULES="`ls 2> /dev/null | grep '\.o$' | head -$UPDBATCH`"
     if [ "$MODULES" = "" ]
     then
        [ "$FORCE" != "" -a -f $ARCHLIBD/$PCKGLIBR ] || continue
     fi

#    Test for recent activity in the tmp directory.
     UPDATE="`find updatelib.* -mtime 0 -print 2> /dev/null`"
     if [ "$UPDATE" != "" ]
     then
#       Get the most recent (should only be one, but...!).
        UPDATE=`ls -t updatelib.* | sed -n 1p`
        echo "An update of $PCKGLIBR by" \
             `echo $UPDATE | sed -e 's/updatelib\.//'` "which began"
        echo "on" `sed -n 1p $UPDATE` "is currently in progress."
        continue
     fi

#    Grab it!
     adate > updatelib.$ID
     LOCKS="$LOCKS $PCKGTMPD/updatelib.*"
     LIBS="$LIBS $PCKGTMPD/$PCKGLIBR"

#    Now we're in business.
     echo "Update $PCKGLIBR ($LEVEL):"

     [ -f $ARCHLIBD/$PCKGLIBR ] && cp $ARCHLIBD/$PCKGLIBR .

     while [ "$MODULES" != "" ]
     do
        case $ARCH in
        sgi*)
#          The SGI prelinker must be invoked explicitly on C++ objects.
           if [ "$LANGUAGE" = C++ ]
           then
              echo "Invoking edg_prelink to instantiate templates..."
              /usr/lib/DCC/edg_prelink $MODULES
           fi
           ;;
        esac

        $ARCHIVE $PCKGLIBR $MODULES
        if [ "$?" != 0 ]
        then
           echo "updatelib: Library update failed, abort!" 1>&2
           exit 2
        fi
        rm -f $MODULES

#       Process the next batch.
        PRVMODS="$MODULES"
        MODULES="`ls 2> /dev/null | grep '\.o$' | head -$UPDBATCH`"

#       Circumvent infinite loops.
        if [ "$MODULES" = "$PRVMODS" ]
        then
           echo "updatelib: Module insertion failed, abort!" 1>&2
           exit 2
        fi
     done

#    Add version.o to the library
     if [ "$NEEDSVERSION" != "" ]; then
          $ARCHIVE  $PCKGLIBR $ARCHLIBD/version.o
     fi

#    Abort if the semaphore file disappears.
     [ -f "$PROCEED" ] || exit 2

#    Update the table of contents.
     if [ "$RANLIB" != : ]
     then
        echo "$RANLIB $PCKGLIBR"
        $RANLIB $PCKGLIBR
     fi
     chmod 664 $PCKGLIBR

#    Abort if the semaphore file disappears.
     [ -f "$PROCEED" ] || exit 2

#    Build the sharable object?
     eval `echo PCKGSEL='$LIB'$PACKAGE`
     if [ "$PCKGSEL" = "" ]
     then
#       Default behaviour if the library control variable is undefined.
        PCKGSEL="static static static static static static"
     fi
     set $PCKGSEL

     case $LANGUAGE in
     C++)
        [ "$LEVEL" = dbg ] && FLAG=$1
        [ "$LEVEL" = opt ] && FLAG=$2
        ;;
     C)
        [ "$LEVEL" = dbg ] && FLAG=$3
        [ "$LEVEL" = opt ] && FLAG=$4
        ;;
     FORTRAN)
        [ "$LEVEL" = dbg ] && FLAG=$5
        [ "$LEVEL" = opt ] && FLAG=$6
        ;;
     *)
        FLAG=""
        ;;
     esac

     if [ "$FLAG" = shatic -o "$FLAG" = shared ]
     then
	VERSION=`avers -b | sed 's/^\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)\ .*/\1/'`
	PCKGLINK=lib$PCKGLANG.$SFXSHAR
        PCKGSHAR=lib$PCKGLANG.$SFXSHAR.$VERSION

        echo ""
        echo "Update $PCKGSHAR ($LEVEL):"

        LIBS="$LIBS $PCKGTMPD/$PCKGSHAR"

        case $ARCH in
        linux* | sun4* | *_gnu | *_egcs | darwin* | osx* )
#          Sharable libraries in SunOS 4.x and 5.x.
           rm -rf BLDSHR.*
           mkdir BLDSHR.$ID
           cd BLDSHR.$ID
           $AR x ../$PCKGLIBR
           rm -f __.SYMDEF*

	   if [ -f "$AIPSARCH/lib$PCKGLANG.purge" ]; then
	      echo ""
	      echo "Using lib$PCKGLANG.purge..."
	      rm -f `cat "$AIPSARCH/lib$PCKGLANG.purge"`
	   fi

	   SHRFAILD=""
           case $LANGUAGE in
             FORTRAN )
	        if [ "$F77LIBD" != "" ]; then
                   FORTLIBS="-L$F77LIBD $F77LIB"
                else
                   FORTLIBS=$F77LIB
		fi
                ;;
             * )
                FORTLIBS=""
                ;;
           esac
#
# Need to add in fortran libs too.
#
           DLIB=`echo LINK$PACKAGE`
	   DYLIBS=""
	   OTHERLIBS_direct=""
	   OTHERLIBS=""

	   ## allow inclusing of fully-qualified file names
	   for i in `eval echo '$'$DLIB`; do
	       if test -e $i; then
		   OTHERLIBS_direct="$OTHERLIBS_direct $i"
	       else
		   if test -n "$found_pkg"; then
	       	       OTHERLIBS="$OTHERLIBS -l$i"
		   else
		       if test "$i" '=' "$PCKGLANG"; then
			   ## stop adding libraries when we encounter the one
			   ## we're currently building... assuming the fortran
			   ## library follows the package library
			   found_pkg="yes"
		       fi
		   fi
	       fi
	   done

           if [ "$dARCH" ]; then
	      if [ "$dARCH" = "osx" ]; then
                  echo $MKSO $LDSOPTS $XTRNPATH -install_name $ARCHLIBD/$PCKGSHAR -o $PCKGSHAR *  -L$ARCHLIBD $OTHERLIBS $OTHERLIBS_direct $XTRNLIBS_shared $FORTLIBS
                  $MKSO $LDSOPTS $XTRNPATH -install_name $ARCHLIBD/$PCKGSHAR -o $PCKGSHAR *  -L$ARCHLIBD $OTHERLIBS $OTHERLIBS_direct $XTRNLIBS_shared $FORTLIBS
	      else
                  echo $MKSO $LDSOPTS $XTRNPATH -o $PCKGSHAR *  -L$ARCHLIBD $OTHERLIBS $OTHERLIBS_direct $XTRNLIBS_shared $FORTLIBS
                  $MKSO $LDSOPTS $XTRNPATH -o $PCKGSHAR *  -L$ARCHLIBD $OTHERLIBS $OTHERLIBS_direct $XTRNLIBS_shared $FORTLIBS
	      fi
           else
              $MKSO $LDSOPTS -Wl,-h,$PCKGSHAR $XTRNPATH -o $PCKGSHAR * -L$ARCHLIBD $OTHERLIBS $OTHERLIBS_direct $XTRNLIBS_shared $FORTLIBS

           fi

           if [ "$?" != 0 ]
           then
              echo "updatelib: Sharable object rebuild failed!" 1>&2
	      echo "updatelib: Only updating static libraries." 1>&2
              cd ..
              rm -rf BLDSHR.*
	      SHRFAILD=true
#               exit 2
           fi

	   if [ "$SHRFAILD" = "" ]
	   then
	      chmod 775 $PCKGSHAR
	      mv $PCKGSHAR ..
	      cd ..
	      rm -rf BLDSHR.*
	   fi
           ;;
        *)
#          Sharable libraries not implemented for other architectures.
           echo "updatelib: Sharable libraries not implemented for $ARCH." 1>&2
           ;;
        esac
     fi

#    Abort if the semaphore file disappears.
     [ -f "$PROCEED" ] || exit 2

#    Signal it as done.
     mv -f updatelib.$ID updatelib.done

  done


# Now to install the updated libraries.
  cd $TMPPCKGD

  if [ ! -f updatelib.lock ]
  then
#    We're first to finish - grab the install lock!
     touch updatelib.lock
     LOCKS="$LOCKS $TMPPCKGD/updatelib.lock"

     UPLIBS=""
     [ "`echo dbg/updatelib.*`" = "dbg/updatelib.*" ] || UPLIBS="$UPLIBS dbg"
     [ "`echo opt/updatelib.*`" = "opt/updatelib.*" ] || UPLIBS="$UPLIBS opt"

     while true
     do
#       Abort if the semaphore file disappears.
        [ -f "$PROCEED" ] || exit 2

#       Wait for everyone else to finish.
        DONE=1
        for UPLIB in $UPLIBS
        do
           [ -f "$UPLIB/updatelib.done" ] || DONE=""
        done
        [ "$DONE" != "" ] && break

        sleep 60
     done

  else
#    Wait for the lock file to disappear before exiting.
     while [ -f updatelib.lock ]
     do
        sleep 15
     done

     rm -f $LIBS $LOCKS $PROCESS

     exit 0
  fi

# Install the updated libraries.
  [ -f dbg/$PCKGLIBR ] && mv -f dbg/$PCKGLIBR $AIPSARCH/libdbg
  [ -f opt/$PCKGLIBR ] && mv -f opt/$PCKGLIBR $AIPSARCH/lib

  if [ "$SHRFAILD" = "" ]
  then
     [ -f dbg/$PCKGSHAR ] && (cd $AIPSARCH/libdbg; rm -f $PCKGLINK.*) && mv -f dbg/$PCKGSHAR $AIPSARCH/libdbg && (cd $AIPSARCH/libdbg; rm -f $PCKGLINK; ln -s $PCKGSHAR $PCKGLINK)
     [ -f opt/$PCKGSHAR ] && (cd $AIPSARCH/lib; rm -f $PCKGLINK.*) && mv -f opt/$PCKGSHAR $AIPSARCH/lib && (cd $AIPSARCH/lib; rm -f $PCKGLINK; ln -s $PCKGSHAR $PCKGLINK)
  fi

# Delete object libraries which are not being maintained.
  case $LANGUAGE in
  C++)
     [ "$1" = defeat ] && rm -f $AIPSARCH/libdbg/lib$PCKGLANG.*
     [ "$1" = static ] && rm -f $AIPSARCH/libdbg/lib$PCKGLANG.$SFXSHAR
     [ "$2" = defeat ] && rm -f $AIPSARCH/lib/lib$PCKGLANG.*
     [ "$2" = static ] && rm -f $AIPSARCH/lib/lib$PCKGLANG.$SFXSHAR
     ;;
  C)
     [ "$3" = defeat ] && rm -f $AIPSARCH/libdbg/lib$PCKGLANG.*
     [ "$3" = static ] && rm -f $AIPSARCH/libdbg/lib$PCKGLANG.$SFXSHAR
     [ "$4" = defeat ] && rm -f $AIPSARCH/lib/lib$PCKGLANG.*
     [ "$4" = static ] && rm -f $AIPSARCH/lib/lib$PCKGLANG.$SFXSHAR
     ;;
  FORTRAN)
     [ "$5" = defeat ] && rm -f $AIPSARCH/libdbg/lib$PCKGLANG.*
     [ "$5" = static ] && rm -f $AIPSARCH/libdbg/lib$PCKGLANG.$SFXSHAR
     [ "$6" = defeat ] && rm -f $AIPSARCH/lib/lib$PCKGLANG.*
     [ "$6" = static ] && rm -f $AIPSARCH/lib/lib$PCKGLANG.$SFXSHAR
     ;;
  esac

  rm -f updatelib.* */updatelib.*


  exit 0
