#!/bin/sh
#-----------------------------------------------------------------------------
# configure: CASA installation script
#-----------------------------------------------------------------------------
#
#   Copyright (C) 2006
#   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: casa-feedback@nrao.edu.
#          Postal address: CASA Project Office
#                          National Radio Astronomy Observatory
#                          520 Edgemont Road
#                          Charlottesville, VA 22903-2475 USA
#
#-----------------------------------------------------------------------------
# Usage: configure 
#-----------------------------------------------------------------------------
# configure is used as the first step in installing CASA either from
# scratch, or to add a new architecture.  In the latter case the
# installation of the casainit scripts and databases can be skipped.
#
# This version modified to allow for binary installations.
#
# Options:
#   None
#
# Status return values correspond to the four phases of the operation
#    0:  success
#    1:  initialization error
#    2:  error fetching required utilities or installing 'gzip'
#    3:  error extracting compressed tar files
#    4:  error installing the casainit scripts or databases
#    5:  error constructing the system directory tree
#    6:  error installing 'gzip' or 'gmake'
#    7:  error installing local makefile and resource definitions
#    8:  unsupported Classic AIPS architecture
#    9:  binary installation failed (no imager)
#
# Original: 1992/04/09 by Mark Calabretta, ATNF
#
# $Id$
#=============================================================================
# Initialize
#-----------------------------------------------------------------------------
# Name of the CASA ftp machine.
  MASTERHOST="casa.nrao.edu"

# Former Option(s)
     SOURCE="yes"

# Editor
  if [ "$VISUAL" != "" ] ; then
     AIPSED=$VISUAL
  elif [ "$EDITOR" != "" ] ; then
     AIPSED="$EDITOR"
  else
     AIPSED=""
  fi

# Issue instructions.
  echo ""
  echo "The 'configure' script bootstraps the CASA system to a state"
  echo "where it maybe build the libraries, binaries, and other parts"
  echo "of the system."
  echo ""
  echo "It may be used to configure CASA from scratch, or to add a"
  echo "new architecture.  In the latter case the installation of the"
  echo "casainit scripts and databases can be skipped."
  echo ""
  echo "You will be asked a few simple questions, most of which have"
  echo "default answers (in square brackets).  Simply type <return> to"
  echo "accept these defaults."
  if [ "$AIPSED" != "" ] ; then
     echo ""
     echo "NOTE: you seem to have a preference for $AIPSED as an editor."
     echo "It will be invoked to edit some files during the installation."
     echo "If this is not acceptable, please interrupt this script, then"
     echo "redefine the EDITOR and/or VISUAL environment variables, and"
     echo "restart this configure script."
  fi
  if [ "$SOURCE" = yes ] ; then
     echo ""
     echo "This is a source build, if you wish a binary installation"
     echo "you will need to fetch the RPMS from ftp.cv.nrao.edu/aips++."
  fi

# Default file creation mask.
  umask 002

  trap 'rm -f $PRINTF $YESNO ; exit' 0 1 2 3 15

# Do we have printf?
  PRINTF=
  (hash printf 2> /dev/null)
  if [ $? != 0 ]
  then
#    No printf, then 'echo -n' probably does the right thing.
#    Not under Solaris it doesn't, so do it empirically.
     PRINTF=printf
     cat > printf << EOT
#!/bin/sh
  if [ "\`echo -n YES\`" = "YES" ] ; then
    echo -n "\$*"
  else
    echo "\$*\c"
  fi
EOT
     chmod 744 printf
  fi

# Shell script for returning yes/no answers.
# It fails if dot is not in your path.

  echo $PATH | grep \\. >/dev/null 2>&1
  if [ $? != 0 ] ; then
     PATH=$PATH:.
  fi

  YESNO=./yesno

  cat > yesno << 'EOT'
#!/bin/sh

  printf " (y/n) [$1]: "

  while true
  do
     read ANSWER DUMMY
     case `echo $ANSWER | tr [A-Z] [a-z]` in
        y | yes) ANSWER=y  ; break ;;
        n | no)  ANSWER=n  ; break ;;
        "")      ANSWER=$1 ; break ;;
        *)       printf "Reenter (y/n) [$1]: " ;;
     esac
  done

  [ "$ANSWER" = y ]

  exit
EOT
  chmod 744 yesno

# Define CASAPATH if necessary.
  if [ "$CASAPATH" != "" ]
  then
     echo ""
     echo "CASAPATH is already defined as"
     echo ""
     echo "$CASAPATH"
     echo ""
     echo "This usually indicates an existing CASA installation."
     printf "Do you wish to proceed?"
     ./yesno y || exit 1
  fi

# Get the CASA root directory.
  AIPSROOT=`pwd`
  case "$AIPSROOT" in
  */code)
     AIPSROOT=`echo $AIPSROOT | sed -e 's#/code$##'`
     echo ""
     echo "Looks like the CASA root directory is $AIPSROOT."
     echo "(This is merely the top-level directory for CASA files)."
     echo ""
     printf "Is this correct?"
     ANSWER=y
     ./yesno y || ANSWER=n
     if [ "$ANSWER" = n ]
     then
        echo ""
        printf "Then what is the CASA root directory? "
        read AIPSROOT DUMMY
        TMPMNT=`(cd $AIPSROOT/code && /bin/pwd) 2> /dev/null`
        CWD=`/bin/pwd`
        [ "$TMPMNT" != "$CWD" ] && AIPSROOT=""
     fi
     ;;
  *)
     AIPSROOT=""
     ;;
  esac

  if [ "$AIPSROOT" = "" ]
  then
     echo ""
     echo "The configure script must be run from the 'code' subdirectory of"
     echo "the CASA root directory.  I cannot proceed till you move there."
     exit 1
  fi

  AIPSCODE="$AIPSROOT/code"
  chmod g+s $AIPSROOT $AIPSCODE

# Check that this script is being run from the right account.
  LOGNAME=${LOGNAME-$USER}
  AIPS2MGR=`cd $AIPSROOT > /dev/null 2>&1; ls -ld . | awk '{ print $3 }'`
  if [ "$AIPS2MGR" != "$LOGNAME" ]
  then
     echo ""
     echo "$AIPSROOT is owned by $AIPS2MGR, and you are $LOGNAME."
     echo "I will not continue under these circumstances, sorry."
     exit 1
  fi

# Redefinitions so we can change directories freely.
  PATH="${AIPSCODE}:$PATH"
  [ "$PRINTF" ] && PRINTF=$AIPSCODE/printf
  YESNO=$AIPSCODE/yesno


#-----------------------------------------------------------------------------
# Check that required utilities are available on this system.
#-----------------------------------------------------------------------------
  echo ""
  echo ""
  echo "Check the availability of required utilities"
  echo "--------------------------------------------"

  echo ""
  echo "The following utilities are used by CASA but not required:"
  echo ">> tex dvips latex latex2html"
  echo ""
  echo "These are available from $MASTERHOST via anonymous ftp."
  echo "You may fetch these and install them yourself later if you wish."

  [ -d $AIPSROOT/import ] || mkdir $AIPSROOT/import
  chmod g+s $AIPSROOT/import
  cd $AIPSROOT/import

  if [ "x$GNUMAKE" = "x" ]
  then 
      GNUMAKE=gmake
  fi
  UTILITIES="gzip $GNUMAKE bison flex perl"

  # We don't need all of these for a binary install... 

  [ "$SOURCE" = no ] && UTILITIES="gzip"

  # let's see if there is a gzip we can use... tricky as we don't know our
  # architecture yet.  Look through them all, if any: in some ways this is
  # silly; you need gunzip to unpack the stuff, and we haven't done that
  # yet.  Catch 22...   This does, however, work if you're restarting an
  # interrupted install. 

  for i in $AIPSROOT/*/bin/gunzip
  do
     if [ -f $i ] ; then

	# got one... try running it and capture all output
	result=`$i 2>&1`
	case $result in
	   gunzip*) # got it.  dirname is not terribly portable, but it'll
		    # do for the beta release...
	      PATH=${PATH}:`dirname $i`;;
	esac
     fi
  done

  echo ""
  echo "The CASA installation does require the following utilities:"
  echo ">> $UTILITIES"

  INSTALL=""
  FETCH=""
  FOUND=""
  for UTILITY in $UTILITIES
  do
     (hash $UTILITY 2> /dev/null)
     if [ $? != 0 ]
     then
        INSTALL="$INSTALL $UTILITY"

        case $UTILITY in
        gzip)
           GZIP="__GZIP"
           KIT="$GZIP"
           ;;
        gmake)
           GMAKE="__GMAKE"
           KIT="$GMAKE"
           ;;
        bison)
           BISON="__BISON"
           KIT="$BISON"
           ;;
        flex)
           FLEX="__FLEX"
           KIT="$FLEX"
           ;;
	perl)
           PERL="__PERL"
           KIT="$PERL"
	   ;;
        esac

        for COMPONENT in $KIT
        do
           [ -f "$COMPONENT" ] || FETCH="$FETCH $COMPONENT"
        done
     else
        FOUND="$FOUND $UTILITY"
     fi
  done

  if [ "$INSTALL" != "" ]
  then
     if [ "$FOUND" != "" ]
     then
        echo ""
        echo "Of these, the following could not be found in your path:"
        echo ">>$INSTALL"
     else
        echo ""
        echo "None of these were found in your path."
     fi

     echo ""
     echo "Your path currently consists of the following directories:"
     for DIR in `echo $PATH | sed -e 's#:# #g'`
     do
        echo "   $DIR"
     done
     echo ""
     printf "Do you want me to quit so you can modify it and start again?"
     yesno n && exit 2

     if [ "$FETCH" != "" ]
     then
        echo ""
        printf "The following kits need to be fetched from "
        echo "$MASTERHOST:"
        echo ">>$FETCH"

        echo "I can do this automatically, otherwise I have to abort"
        printf "and let you do it.  Continue?"
        yesno y || exit 2

        echo "I will fetch them into $AIPSROOT/import."

        echo "open $MASTERHOST" > /tmp/ftp$$
        echo "user ftp configure" >> /tmp/ftp$$
        echo "verbose" >> /tmp/ftp$$
        echo "binary" >> /tmp/ftp$$
        echo "hash" >> /tmp/ftp$$
        echo "cd pub/import" >> /tmp/ftp$$
        echo "mget $FETCH" >> /tmp/ftp$$
        echo "get VERSION" >> /tmp/ftp$$
        echo "quit" >> /tmp/ftp$$

        rm -f VERSION

        echo ""
        echo "Attempting ftp to $MASTERHOST..."

#       Connect to the master host and get the files.
        ftp -in < /tmp/ftp$$
        rm -f /tmp/ftp$$

        if [ ! -f VERSION ]
        then
           echo ""
           echo "Failed to fetch$FETCH."
           echo "Your internet connection may be down, in which case"
           echo "you should try rerunning 'configure' at a later time."
           exit 2
        fi
     fi

#    Install 'gzip' if necessary.
     if `echo $INSTALL | grep gzip > /dev/null 2>&1`
     then
        echo ""
        echo "Extract 'gzip' sources from $GZIP..."

        tar pvxf "$GZIP"
        if [ "$?" = 0 ]
        then
           echo ""
           echo "Compile 'gzip'..."

           cd gzip-*
           ./configure
           mkdir bin man man/man1
           make prefix=. install
           if [ "$?" = 0 ]
           then
#             Add it to the PATH.
              PATH=`pwd`/bin:$PATH

              echo ""
              gzip --version
              if [ "$?" = 0 ]
              then
                 echo ""
                 echo "The installation appears to have succeeded."
              else
                 echo ""
                 echo "Test execution of 'gzip' failed."
                 exit 2
              fi
           else
              echo ""
              echo "Failed to install 'gzip'."
              exit 2
           fi
        else
           echo ""
           echo "Failed to extract the 'gzip' tar file."
           exit 2
        fi

        INSTALL=`echo $INSTALL | sed -e 's#gzip##'`
     fi

     INSTALL=$INSTALL
     if [ "$INSTALL" != "" ]
     then
        echo ""
        echo "The following will be installed later:"
        echo ">>$INSTALL"
     fi
  else
     echo ""
     echo "All appear to be available."
  fi

#-----------------------------------------------------------------------------
# Install the casainit scripts and construct the aipshosts database
#-----------------------------------------------------------------------------
  cd $AIPSCODE

  echo ""
  echo ""
  echo "Begin installation of the casainit scripts and databases"
  echo "--------------------------------------------------------"

  for AIPSINIT in casainit.sh casainit.csh
  do
     if [ -f "$AIPSROOT/$AIPSINIT" ]
     then
        echo ""
        echo "$AIPSROOT/$AIPSINIT already exists."
        printf "Overwrite it?"
        yesno y || continue
        chmod +w $AIPSROOT/$AIPSINIT
     fi

#    Check that it exists in the install subdirectory.
     if [ ! -f install/$AIPSINIT ]
     then
        echo ""
        echo "Cannot find $AIPSROOT/install/$AIPSINIT, I must stop now."
        exit 4
     fi

     sed -e "s#__AIPSROOT#$AIPSROOT#g" install/$AIPSINIT > \
        $AIPSROOT/$AIPSINIT
  done

# Construct the aipshosts database.
  HOSTFILE="$AIPSROOT/aipshosts"
  HOST=`uname -n | awk -F. '{ print $1 }'`

# Hazard a guess at arch based on uname...
  case `uname -s` in
     SunOS)
        case `uname -r` in
           5*) ARCH="sun4sol_gnu";;
	esac;;
     HP-UX)      ARCH="hpux_gnu";;
     OSF1|ALPHA) ARCH="alpha_gnu";;
     Linux)      ARCH="linux_gnu";;
     Darwin)     ARCH="darwin";;
     IRIX*)      ARCH="sgi_64b";;
  esac
  echo "$AIPS_ROOT/HOSTS.LIST"

# Use Classic AIPS HOSTS.LIST file if found...
  if [ -f $AIPS_ROOT/HOSTS.LIST ] ; then

     echo "$AIPS_ROOT/HOSTS.LIST"
     # but only if there's an entry for this host 
     entry=`cat $AIPS_ROOT/HOSTS.LIST | grep '^+' | grep -i $HOST | head -1`
     if [ "$entry" != "" ]
     then

	# extract info for this host from that line.  "set -" as the 
	# first char will be a "+" sign.
	set - $entry
	ARCH=$3
	SITE=`echo $4 | tr '[A-Z]' '[a-z]'`
	shift; shift; shift; shift; shift
	COMMENT=$*

	# translate AIPS ARCH to CASA ARCH
	case $ARCH in
	   ALPHA)   ARCH="alpha_gnu";;
	   HP*)     ARCH="hpux_gnu";;
	   LINUX)   ARCH="linux_gnu";;
	   SGI)     ARCH="sgi_64b";;
	   SOL|SUL) ARCH="sun4sol_gnu";;
	   *)       ARCH="";;
	esac

	# only proceed further with translation if it's a known architecture
	if [ "$ARCH" != "" ]
	then

	   echo ""
	   echo "A Classic AIPS file HOSTS.LIST was found in $AIPS_ROOT"
	   echo "Using it, the suggested name for your CASA site is $SITE"
	   echo "and the architecture for the current host is $ARCH."
	   echo ""
	   echo "Each CASA installation has a default architecture, usually"
	   echo "reflecting the system of which you have the most.  This is"
	   echo "referred to as the default in the aipshosts file."
	   echo ""
	   CONVDEF=n
	   printf "Do you want to accept $SITE and $ARCH as the DEFAULT?"
	   yesno y && CONVDEF=y

	   if [ "$CONVDEF" = y ]
           then

	      # save old version just in case
	      if [ -f $HOSTFILE ]
	      then
		 echo "Moving $HOSTFILE"
		 echo "    to $HOSTFILE.old"
		 mv $HOSTFILE $HOSTFILE.old
	      fi

	      # Make initial entry
	      echo "# CASA host database" >$HOSTFILE
	      echo "" >>$HOSTFILE
	      echo "DEFAULT $ARCH $SITE" | \
	       awk '{ print sprintf("%-15s %-15s %-15s ",$1,$2,$3) }' | \
	       unexpand -a >>$HOSTFILE

	      # We can do more if you REALLY want us to...
	      echo ""
	      echo "In addition, this file can be used to create the CASA"
	      echo "equivalent file, $HOSTFILE."
	      echo "Information will be automatically extracted for all hosts"
	      echo "with a supported architecture."
	      echo ""
	      CONVERT=n
	      printf "Do you want to do this?"
	      yesno y && CONVERT=y
	      
	      if [ "$CONVERT" = y ]
  	      then

		 # I cheat here.  The comments shouldn't be lowercased,
		 # but awk doesn't have a built-in "tr".
		 cat $AIPS_ROOT/HOSTS.LIST | grep '^+' | tr '[A-Z]' '[a-z]' | \
		  awk '{
		    narch = "none"
		    if ($3 == "alpha") { narch = "alpha_gnu" } 
		    if ($3 == "hp")    { narch = "hpux_gnu" }
		    if ($3 == "hp2")   { narch = "hpux_gnu" }
		    if ($3 == "linux") { narch = "linux_gnu" }
		    if ($3 == "sgi")   { narch = "sgi_64b" }
	            if ($3 == "sol")   { narch = "sun4sol_gnu" }
	            if ($3 == "sul")   { narch = "sun4sol_gnu" }
		    if (narch == "none") {
		       printf("Skipping arch %s for %s\n",$3,$2) | "cat 1>&2"
		    } else {
		 	 printf("%-15s %-15s %-15s ",$2,narch,$4)
		 	 for (j=6; j<=NF; j++) {
			    printf "%s ", $j
		 	 }
		 	 printf ("\n")
		    }  
		  }' | unexpand -a >>$HOSTFILE
	      else

		 # Installer does not want to slurp in HOSTS.LIST, but
		 # does want to get info for this host (we assume).

		 echo "Very well, will only make one entry for this host."
		 ENTRY=`echo "$HOST $ARCH $SITE" | \
		  awk '{ print sprintf("%-15s %-7s %-15s ",$1,$2,$3) }' | \
		  unexpand -a`
		 ENTRY="$ENTRY$COMMENT"
		 echo "$ENTRY" >>$HOSTFILE

	      fi

	      echo ""
	      echo "new version of $HOSTFILE generated."
	      echo "This file specifies all the hosts which run CASA."
	      echo "It must have an entry for each host, with the SITE name"
	      echo "architecture, and a comment.  The info from HOSTS.LIST"
	      echo "in your Classic AIPS ($AIPS_ROOT) installation was used to"
	      echo "make a best guess at what you will want in this file."
	      echo "Please check this file for accuracy and edit as needed."
	      [ "$AIPSED" != "" ] && $AIPSED $HOSTFILE
	      printf "Press RETURN when ready to proceed..."; read dum
	      echo ""
	      echo "Now about to check this file..."
	      echo ""
	   fi
	   # end check on accepting AIPS site and translated arch as default
	fi
	# end of check on known CASA architecture
     fi
     # end of check on entry for this host in HOSTS.LIST
  fi

  echo "$HOSTFILE"

  if [ ! -f $HOSTFILE ] ; then

     echo ""
     echo "There must be an entry in $HOSTFILE for"
     echo "every machine on which you intend to run CASA.  The next section"
     echo "will construct these entries."
     echo ""
     echo "The local SITE name will be used to create site-specific"
     echo "directories.  It should be a SINGLE lower-case word of less than"
     echo "than eight characters, usually reflecting the geographical location"
     echo "(town or city) rather than institution, since the latter may have"
     echo "several sites.  Do not put any 'funny' characters (eg '/') in it." 
  fi

  while true
  do
     UPDATE=y

     if [ -f "$HOSTFILE" ]
     then
        echo ""

        ENTRY=`grep "$HOST" "$HOSTFILE"`
        if [ "$ENTRY" != "" ]
        then
           echo "$HOSTFILE has the following entry for $HOST:"
           echo "$ENTRY"
           printf "Is this correct?"
           yesno y && UPDATE=n

           if [ "$UPDATE" = y ]
           then
              set $ENTRY
              HOST=$1 ; shift
              ARCH=$1 ; shift
              SITE=$1 ; shift
              COMMENT=$*
           fi
        else
           echo "$HOSTFILE doesn't have an entry for $HOST."
        fi
     else
        touch "$HOSTFILE"
     fi

     if [ "$UPDATE" = y ]
     then
	if [ "$AIPS_VERSION" != "" ] ; then
	   # watch for Classic AIPS's ARCH variable
	   case $ARCH in
	      ALPHA)  ARCH="alpha_gnu";;
	      HP*)    ARCH="hpux_gnu";;
	      LINUX)  ARCH="linux_gnu";;
	      SGI)    ARCH="sgi_64b";;
	      S[OU]L) ARCH="sun4sol_gnu";;
	      *)      ARCH="";;
	   esac
	fi
        echo ""
        echo "Recognized systems:"
        echo ""
        echo "   alpha_gnu     DEC/Alpha OSF/1, GNU C++ compiler (g++)"
        echo "   hpux_gnu      Hewlett-Packard/HP9000 HPUX, GNU C++ compiler"
	echo "   linux_gnu    Linux/RedHat-5.x, x>0 (Intel only) gnu compiler"
	echo "   linux_64b    Linux/RedHat-5.x, x>0 (Intel only) 64bit compilergnu compiler"
	echo "   linux         same as linux_gnu"
        echo "   sgi_64b       Silicon Graphics IRIX 7.x, SGI C++ compiler"
        echo "   sgi_ntv       same as sgi"
        echo "   sun4sol_gnu  Sun/Sparc Solaris 2.x, GNU/EGCS C++ compiler (g++)"
        echo "   sun4sol       same as sun4sol_gnu"
        echo "   darwin       Mac OS X"
        echo ""
	if [ "$ARCH" != "" ] ; then
	   if [ "$ARCH" != "$NARCH" -a "$NARCH" != "" ] ; then
	      echo "This system may be of architecture $NARCH"
	   fi
	fi

        while true
        do
#          Get this machine's architecture.
           ARCHS="alpha_gnu hpux_gnu linux linux_gnu linux_64b sgi_ntv sgi_64b sun4sol_gnu sun4sol darwin"
           echo ""
           echo "What is $HOST's architecture?"
           printf "($ARCHS) [$ARCH]: "
           while true
           do
              read ANSWER DUMMY
              [ "$ANSWER" != "" ] && ARCH="$ANSWER"
              case " $ARCHS " in
              *" $ARCH "*)
                 break
                 ;;
              esac
              printf "Recognized values ($ARCHS): "
           done

#          Get the local site name.
           SITES=""
           if [ "$ARCH" = "darwin" ]; then
			echo -n "searching for pre-defined sites..."
           	cpuarch=$(uname -m)
			sites=($(ls ${AIPSROOT}/${ARCH}/*/makedefs | sed -e 's,.*/\(.*\)/makedefs,\1,'))
			for i in ${sites[@]}
			  do
				SITES="$SITES $i"
				[ ${i%${cpuarch}} = $i ] || SITE=$i
			  done
			echo $SITES
           fi
           echo ""
           printf "What is $HOST's site name? ($SITES) [$SITE]: "
           while true
           do
              read ANSWER DUMMY
              [ "$ANSWER" != "" ] && SITE="$ANSWER"
              if [ "$SITE" != "" ] ; then
		 case $SITE in
                    */*|*/|/*) echo "You cannot put a slash in a site name.";;
		    *)   break;;
		 esac
	      fi
              printf "Please re-enter the site name: "
           done

#          Get a short comment.
           echo ""
           echo "You may enter a short comment, at most 40 characters:"
           [ "$COMMENT" != "" ] && echo "[$COMMENT]:"
           read ANSWER
           [ "$ANSWER" != "" ] && COMMENT="$ANSWER"

#          Construct a new aipshosts entry.
           ENTRY=`echo "$HOST $ARCH $SITE" | \
              awk '{ print sprintf("%-15s %-7s %-15s ",$1,$2,$3) }' |
              unexpand -a`
           ENTRY="$ENTRY$COMMENT"

           echo ""
           echo "The new aipshosts entry for $HOST will be"
           echo "$ENTRY"
           printf "Is this correct?"
           yesno y || continue

#          Update aipshosts.
           awk '{
                   if ($1==aipshost) {
                      if (a==0) {print entry ; a=1}
                   }
                   else {
                      print
                   }
                }
                END {
                   if (a==0) {
                      print entry
                   }
                }' aipshost="$HOST" entry="$ENTRY" \
                $HOSTFILE > /tmp/aipshosts$$
           mv -f /tmp/aipshosts$$ $HOSTFILE

           break
        done
     fi

#    More punishment?
     echo ""
     echo "The current state of the aipshosts database is:"
     echo "------------------------------------------------------------"
     cat $HOSTFILE
     echo "------------------------------------------------------------"

     echo ""
     echo "You may modify none, any or all entries listed here, and/or"
     echo "add entries for additional hosts."
     echo ""
     printf "Do you wish to add or modify any entries?"
     yesno n || break

     echo ""
     printf "Enter the machine name: "
     read HOST DUMMY
     while [ "$HOST" = "" ]
     do
        printf "Not understood, reenter: "
        read HOST
     done
  done

# Now that we've got casainit - use it!
  . $AIPSROOT/casainit.sh

# And tell everyone else to do likewise.
  echo ""
  echo "Intending CASA users who use C-like shells (csh, tcsh) must put the"
  echo "following line in their .login file at a point AFTER the PATH (and"
  echo "MANPATH) variables are defined:"
  echo ""
  echo "   source $AIPSROOT/casainit.csh"
  echo ""
  echo "Likewise, users of Bourne-like shells (sh, bash, ksh, zsh) must modify"
  echo "their .profile file similarly:"
  echo ""
  echo "   . $AIPSROOT/casainit.sh"
  echo ""
  echo "The casainit scripts will define the CASAPATH environment variable,"
  echo "and modify PATH and MANPATH for CASA.  See the CASA System manual"
  echo "entry for casainit(1) for more information."
  echo ""
  printf "Press <return> to continue:"
  read ANSWER


#-----------------------------------------------------------------------------
# Construct the system directory tree(s)
#-----------------------------------------------------------------------------
  echo ""
  echo ""
  echo "Create system directories for each architecture"
  echo "-----------------------------------------------"

# Read through the aipshosts file.  Avoid comment lines.
  ARCHS=""
  cat $HOSTFILE | grep -v '^#' | awk '{print $1 " " $2 " " $3}' |
  {
     exec 3<&0 0</dev/null

     while read HOST ARCH SITE 0<&3
     do
        AIPSARCH="$AIPSROOT/$ARCH"

        echo ""
        echo "Processing $HOST"

        case "$ARCHS " in
        *" $ARCH "*)
           ;;
        *)
           if [ ! -d $AIPSROOT/$ARCH ]
           then
              mkdir $AIPSROOT/$ARCH
              chmod g+s $AIPSROOT/$ARCH
              echo "Created $AIPSROOT/$ARCH"
           fi

           for DIR in \
              lib libdbg libexec \
              bin bindbg \
	      aux \
              tmp \
              tmp/aips \
              tmp/aips/dbg \
              tmp/aips/opt \
              tmp/aips_f \
              tmp/aips_f/dbg \
              tmp/aips_f/opt \
              doc \
              doc/man1 \
              doc/cat1 \
              $SITE
           do
              if [ ! -d $AIPSARCH/$DIR ]
              then
                 mkdir $AIPSARCH/$DIR
                 echo "Created $AIPSARCH/$DIR"
              fi
           done

           ARCHS="$ARCHS $ARCH"
           ;;
        esac

        if [ ! -d $AIPSARCH/$SITE/$HOST ]
        then
           mkdir $AIPSARCH/$SITE/$HOST
           echo "Created $AIPSARCH/$SITE/$HOST"
        fi

     done
  }

# Reset vital parameters.
  set $CASAPATH
  HOST=$1 ; shift
  ARCH=$1 ; shift
  SITE=$1
  AIPSARCH="$AIPSROOT/$ARCH"
  echo "System directory construction apparently completed"
  echo ""

#-----------------------------------------------------------------------------
# Fetch bug fixes
#-----------------------------------------------------------------------------
# ...
# What bugs?


#-----------------------------------------------------------------------------
# If necessary, relocate 'gzip' and install 'gmake'
#-----------------------------------------------------------------------------

  if [ "$GZIP" != "" ]
  then
     echo ""
     echo "Relocate the 'gzip' installation to below $AIPSARCH..."

     ( cd $AIPSROOT/import/gzip-*; mv -f bin/* $AIPSARCH/bin )
     ( cd $AIPSROOT/import       ; rm -rf $AIPSROOT/import/gzip-* )

     echo "...done."
     echo ""
  fi

  if [ "$SOURCE" = yes ] ; then
     (hash $GNUMAKE 2> /dev/null)
     if [ $? != 0 ]
     then
        echo ""
	echo ""
	echo "Install GNU make"
	echo "----------------"

	cd $AIPSROOT/import

	if [ -f "$GMAKE" ]
	then
           echo ""
	   echo "Extract GNU make sources from $GMAKE..."

	   gunzip -c "$GMAKE" | tar pvxf -
	   if [ "$?" != 0 ]
	   then
              echo ""
	      echo "Failed to extract $GMAKE, I must stop now."
	      exit 6
	   fi
	fi

	DIR=`echo $GMAKE | sed -e 's#.tar.gz##'`
	cd $DIR

#       Build it using ordinary make.
	echo ""
	echo "Compile GNU make using ordinary make..."

	./configure
	make instname=gmake bindir=$AIPSARCH/bin infodir=/tmp \
	 mandir=$AIPSARCH/doc/man1 manext=1 install_setgid=false all install
	if [ "$?" = 0 ]
	then
           echo ""
	   gmake --version
	   echo "GNU make installed successfully, (but without load" \
	    "average checking)."
	   echo ""
        else
           echo ""
	   echo "The installation of GNU make failed, I must stop now."
	   exit 6
	fi

	cd $AIPSROOT/import
	printf "Can I delete the $AIPSROOT/import/$DIR directory?"
	yesno y && rm -rf $AIPSROOT/import/$DIR
     fi
  fi

#-----------------------------------------------------------------------------
# Construct the local aipsrc and makedefs files -- and aips++local
#-----------------------------------------------------------------------------

  echo "Architecture-specific definitions needed for CASA"
  echo "($AIPSARCH/aips++local.sh)"

  script=$AIPSARCH/aips++local.sh
  if [ -f $script ] 
  then
     echo ""
     echo "Found existing $script file"
     echo "This procedure will ASSUME the correct definitions for"
     echo ""
     echo "   PGPLOT_FONT (location of grfont.dat) and"
     echo "   LD_LIBRARY_PATH (location of pgplot and other shared libraries)"
     echo ""
     echo "have been entered in this file where needed."
  else
     echo ""
     echo "No $script file found;"
     echo "I will create a new one... (it defines system resources for the"
     echo " aips++ startup)"  
     echo ""
     echo '#!/bin/sh' >$script
     echo "# Local required definitions for CASA" >>$script
     echo "# This is to define PGPLOT_FONT and LD_LIBRARY_PATH" >>$script
     echo "# where required." >>$script
     echo "#--------------------------------------------------------" >>$script
     if [ "$PGPLOT_FONT" = "" ] ; then
        # see if PGPLOT is anywhere obvious...
	PGPLOT_FONT=$AIPSARCH/lib/grfont.dat
        for i in /usr/lib /usr/local/lib /opt/casa/01/lib /opt/local/lib /usr/local/pgplot \
	         /opt/local/pgplot /usr/lib/pgplot /usr/local/lib/pgplot \
		 /opt/local/lib/pgplot
        do
           if [ -f $i/grfont.dat ] ; then
	      PGPLOT_FONT=$i/grfont.dat; break
	   fi
        done
	# allow for smart users to set it themselves...
	echo "if [ \"\$PGPLOT_FONT\" = \"\" ] ; then" >>$script
        echo "   PGPLOT_FONT=$PGPLOT_FONT; export PGPLOT_FONT" >>$script
	echo "fi" >>$script
     else
        echo "# configure found PGPLOT_FONT=$PGPLOT_FONT" >>$script
	echo "# on `date` and assumed it was valid." >>$script
     fi
     case $ARCH in
	sun*|linux*)

	   # these systems use LD_LIBRARY_PATH.  The potential for screwups
	   # are considerable.  Rather than trying to get it set up right
           # for any possible weird or bizarre setup, just prepend the 
	   # necessary $AIPSARCH/lib area.
	   echo "if [ \"\$LD_LIBRARY_PATH\" = \"\" ] ; then" >>$script
	   echo "   LD_LIBRARY_PATH=$AIPSARCH/lib" >>$script
	   echo "else" >>$script
	   echo "   LD_LIBRARY_PATH=$AIPSARCH/lib:\$LD_LIBRARY_PATH" >>$script
	   echo "fi" >>$script
	   echo "export LD_LIBRARY_PATH" >>$script

	   ;;
     esac
  fi

  echo "Collation of local resource definitions (aipsrc)"
  echo "------------------------------------------------"

  if [ ! -f $AIPSARCH/aipsrc ] ; then
     atemp=$AIPSROOT/code/install/aipsrc
     if [ ! -f $atemp ] ; then
        echo ""
	echo "A template 'aipsrc' file was not found.  I Searched for it"
	echo "and $AIPSROOT/code/install/aipsrc"
	echo "and $AIPSARCH/aipsrc"
	echo "I cannot proceed and must stop now."
	exit 7
     fi
     echo "Copying template $atemp"
     echo "              to $AIPSARCH/aipsrc"
     cp $atemp $AIPSARCH/aipsrc
     chmod +x $AIPSARCH/aipsrc
  fi

  if [ ! -f $AIPSARCH/$SITE/aipsrc ]
  then
     # this relative pathname does NOT work.
     # if [ ! -f $ARCH/aipsrc.template ]
     if [ ! -f $AIPSROOT/code/install/$ARCH/aipsrc.template ]
     then
        echo ""
        echo "Template aipsrc file for $ARCH not found!  Abandoning configure!"
	echo "(looked for $AIPSROOT/code/install/$ARCH/aipsrc.template and"
	echo " $AIPSARCH/$SITE/aipsrc, neither found; cannot proceed.)"
        exit 7
     fi

     cp $AIPSROOT/code/install/$ARCH/aipsrc.template $AIPSARCH/$SITE/aipsrc
     chmod +wx $AIPSARCH/$SITE/aipsrc
  fi

  # add some essential items...
  echo "" >>$AIPSARCH/$SITE/aipsrc
  echo "#----------------------------------------------------------------" \
   >>$AIPSARCH/$SITE/aipsrc
  echo "# Configure added the following estimates of required parameters:" \
   >>$AIPSARCH/$SITE/aipsrc
  echo "# system memory, number of processors." \
   >>$AIPSARCH/$SITE/aipsrc
  echo "# You must change any that have the word 'define_me' in uppercase" \
   >>$AIPSARCH/$SITE/aipsrc
  echo "" >>$AIPSARCH/$SITE/aipsrc

  
  mem="DEFINE_ME"
  psr="DEFINE_ME"
  case $ARCH in
      sun*)
	  mem=`dmesg | grep '^mem' | head -1 | sed -e 's/.*= \([0-9]*\)K.*/\1/'`
	  mem=`expr $mem / 1024`
	  if [ -f /usr/sbin/psrinfo ] ; then
	      psr=`/usr/sbin/psrinfo | wc -l`
	  fi
	  ;;
      linux*)
	  if [ -f /proc/meminfo ] ; then
	      ## This wouldn't have worked even in RHEL4:
	      # mem=`cat /proc/meminfo | grep ^Mem: | awk '{print $2}'`
	      ## Possibly more portable:
	      # mem=$(free | grep Mem | awk '{print $2}')
	      mem=$(cat /proc/meminfo | grep ^MemTotal: | awk '{print $2}')
	      mem=$(expr 2 + $mem / 1024 / 1024)
	  fi
	  if [ -f /proc/cpuinfo ] ; then
	      # Using cat just in case grep can't process /proc/cpuinfo directly.
	      psr=$(cat /proc/cpuinfo | grep processor | wc -l)
	  fi
	  ;;
      darwin*) 
	  psr=$( sysctl -n hw.ncpu )
	  # NOTE: bwaters: sysctl hw.physmem WONT WORK - it maxes out at 2GB...
	  pagesize=$(sysctl -n hw.pagesize); pages=0;
	  for i in $(vm_stat |head -n 5 | tail -n -4|cut -c 20-36 )
	      do pages=$(( $pages + $i ));
	  done
	  mem=$(( $pages * $pagesize / 1024 / 1024 ))
	  ;;
  esac
  if [ "$mem" = "DEFINE_ME" ] ; then
    echo ""; printf "How much memory (Mbytes) does your system have? "
    read mem
  fi
  if [ "$psr" = "DEFINE_ME" ] ; then
    echo ""; printf "How many processors does your system have? "; read psr
  fi
  echo ""
  echo "Setting memory to $mem and number of processors to $psr"
  echo "in the $AIPSARCH/$SITE/aipsrc file."
  #
  #Don't set the memory size as bad things can happen
  #
  #echo  "system.resources.memory: $mem" >>$AIPSARCH/$SITE/aipsrc
  echo "system.resources.numcpu: $psr" >>$AIPSARCH/$SITE/aipsrc

  echo ""
  echo "The default system configuration parameters are set in"
  echo "$AIPSROOT/$ARCH/aipsrc though you"
  echo "should NOT have to edit this file.  There is a site- and architecture-"
  echo "specific version of this file in"
  echo ""
  echo "   $AIPSROOT/$ARCH/$SITE/aipsrc"
  echo ""
  echo "that you DO need to edit.  If you require even more granularity, you"
  echo "can have a host-specific aipsrc file in subdirectory"
  echo "subdirectory $AIPSROOT/$ARCH/$SITE/`uname -n`/"
  echo "And if that's not enough, users may also have their own .aipsrc"
  echo "files in their login directories." 
  echo ""
  uid=`id | sed -e 's/^[^(]*(//' -e 's/).*//'`
  gid=`id | awk '{print $2}' | sed -e 's/^[^(]*(//' -e 's/).*//'`
  cat $AIPSARCH/$SITE/aipsrc | \
   sed -e "s/^# account\([^:]*\):.*/account\1: $uid.$gid/g" \
   >$AIPSARCH/$SITE/aipsrc.new
  rm -f $AIPSARCH/$SITE/aipsrc; 
  mv $AIPSARCH/$SITE/aipsrc.new $AIPSARCH/$SITE/aipsrc

  echo "The account definitions are mainly to say who is the CASA manager."
  echo "In the aipsrc file, it is specified in the form 'user.group'; this"
  echo "script will use your current account to set this parameter."
  echo "Your username is $uid and your group is $gid"
  echo "If these are not what you want in the aipsrc file as the CASA"
  echo "manager, change them when you edit that file."
  echo ""

# while we could guess the printers from /etc/printcap if present a la 
# INSTEP1 in Classic AIPS, there's no easy way to guess the default paper
# format.  Timezone might give us some hints, but that's a bit hairy...

  echo "The printer sizes are, e.g. 'A4', 'A3', or 'letter' (paper size)."
  echo "You need to set the default printer, and printer size in the file."
  echo "Please remove the comment '#' characters from the lines you change."
  echo ""
  echo "For any other parameters, see the release notes or install manual."
  echo ""

  if [ "$AIPSED" != "" ] 
  then
     echo "About to edit $AIPSARCH/$SITE/aipsrc with $AIPSED..."
     $AIPSED $AIPSARCH/$SITE/aipsrc
     printf "Press <return> when ready to proceed..."; read ANSWER
  else
     echo ""
     echo "You should do this now in another window, or you can suspend"
     echo "this job with ^Z (or whatever your suspend code is)."
     printf "Press <return> when you've finished: "
     read ANSWER
  fi

# Check that all DEFINE_MEs were resolved.
  while true
  do
     nitem=`cat $AIPSARCH/$SITE/aipsrc | grep DEFINE_ME | wc -l`
     [ $nitem -eq 0 ] && break
     echo ""
     echo "Found $nitem unresolved 'DEFINE_ME's still remain in the file"
     echo "$AIPSARCH/$SITE/aipsrc"
     echo "Please resolve all of them by deleting the line completely"
     echo "or changing the 'DEFINE_ME' to '(defaults)'"
     if [ "$AIPSED" != "" ] ; then
	printf "Press <return> to edit the file..."; read ANSWER
	$AIPSED $AIPSARCH/$SITE/aipsrc
     fi
     printf "Press <return> to continue... "; read ANSWER
  done

  echo ""
  echo ""
  echo "Collation of local makefile definitions (makedefs)"
  echo "--------------------------------------------------"

  cd $AIPSCODE/install

  if [ ! -f $AIPSARCH/makedefs ]
  then
     if [ ! -f makedefs ]
     then
        echo ""
        echo "Default makedefs file not found, I must stop now."
        exit 7
     fi

     cp makedefs $AIPSARCH/makedefs
     chmod +x $AIPSARCH/makedefs
  fi

  if [ ! -f $AIPSARCH/$SITE/makedefs ]
  then
     if [ ! -f $ARCH/makedefs.template ]
     then
        echo ""
        echo "Template makedefs file for $ARCH not found, I must stop now."
        exit 7
     fi

     cp $ARCH/makedefs.template $AIPSARCH/$SITE/makedefs
     chmod +wx $AIPSARCH/$SITE/makedefs
  fi

  echo ""
  echo "The next step is to define local variables used by make.  Default"
  echo "definitions are made in"
  echo ""
  echo "   $AIPSROOT/$ARCH/makedefs"
  echo ""
  echo "and site-specific definitions should be made by editing"
  echo ""
  echo "   $AIPSROOT/$ARCH/$SITE/makedefs"
  echo ""
  echo "accordingly.  Host-specific makedefs files may also be created if"
  echo "required in the host-specific subdirectories of the above directory."
  if [ "$AIPSED" != "" ] 
  then
     $AIPSED $AIPSARCH/$SITE/makedefs
     printf "Press <return> when ready to proceed..."; read ANSWER
  else
     echo ""
     echo "You should do this now in another window, or you can suspend"
     echo "this job with ^Z (or whatever your suspend code is)."
     printf "Press <return> when you've finished: "
     read ANSWER
  fi

# Verify makedefs definitions.
  while true
  do
     echo ""
     echo "Verifying makedefs definitions..."
     $GNUMAKE -f $AIPSARCH/makedefs test_global

     echo ""
     echo "Error levels are:"
     echo ""
     echo "  ADVISORY: A correction may be needed depending on the"
     echo "            availability of resources such as libraries or modes"
     echo "            of compiler operation."
     echo ""
     echo "   WARNING: An incorrect definition was found which should be"
     echo "            fixed otherwise parts of the build will fail."
     echo ""
     echo "   SERIOUS: A fundamental problem was found which will cause the"
     echo "            build to fail."
     echo ""
     echo "If you need to make corrections you should do it now."
     echo ""
     echo "Press return to continue"
     read ANSWER
     echo ""
     printf "Do you want to reverify your makedefs?"
     yesno n || break
  done


#-----------------------------------------------------------------------------
# Build CASA
#-----------------------------------------------------------------------------
  echo ""
  echo ""
  echo "Build CASA configure bootstrap for $ARCH"
  echo "------------------------------------------"
  echo "The CASA bootstrap will now be built, no further questions will be"
  echo " asked.  A copy of the log of the build will be preserved in"
  echo ""
  echo "   \"$AIPSCODE/build.log\""
  echo ""
  echo "Should you need to redo the configure bootstrap , for example because"
  echo "you discover that some of your \"makedefs\" definitions were "
  echo "inappropriate, you can do so as $AIPS2MGR via:"
  echo ""
  echo "   cd $AIPSCODE"
  echo "   $GNUMAKE -C install allsys"
  echo ""
  echo "Building the boostrap..."
  echo ""

# Begin the installation.
  cd $AIPSCODE
  export CASAPATH
  echo $CASAPATH
  $GNUMAKE -C install allsys > build.log 2>&1

# Mark it as done.
  if [ -f VERSION ]
  then
     VERSION=`sed -n 1p VERSION | awk '{ print $1 }'`

     cd $AIPSROOT/$ARCH

     [ -f LOGFILE ] || touch LOGFILE
     mv -f LOGFILE LOGFILE_
     echo $VERSION `date -u "+%a %Y/%m/%d %T"` "GMT  (base)" | \
        cat - LOGFILE_ > LOGFILE

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

     chmod 444 VERSION LOGFILE
     rm -f VERSION_ LOGFILE_
  fi

  echo ""
  echo "CASA bootstrap build  ended at "`date -u "+%a %Y/%m/%d %T"`" GMT."
  echo "You may now build CASA via:"
  echo ""
  echo "sneeze -l -m cumulative&"
  echo ""

  exit 0
