#!/bin/sh
#
# Copyright(c) 1998, Space Science and Engineering Center, UW-Madison
# Refer to "McIDAS Software Acquisition and Distribution Policies"
# in the file  mcidas/data/license.txt
#
#	$Id: mcinst.sh,v 1.61 2004/12/16 19:49:35 davep Exp $
#
#-------
# This is the all-in-one unpack+make+install script.
#
# It assumes you have a tar file named foo.tar.Z or foo.tar in the
# current directory, where foo is the basename of this script.
#
# For instance, if this script is called 'openadde.sh', then it
# assumes there is a file called 'openadde.tar.Z' or a file called
# 'openadde.tar' in the current directory.
#
# It further assumes that when you unpack the tar file you get a
# directory with the same basename.  For instance, that you get a
# directory named 'openadde'.
#
#-------

#-------
#Check for valid previous version
#-------

check_version()
{
     # Check if this is an incremental update if not continue as normal
     inc_word=`echo $base|cut -c13-15`
     baseroot=`basename $base _inc`
     if [ $act = "make" ] ; then
        if [ "$inc_word" = "inc" ] ; then
           unset latest_ver
           ft_ver=`echo $base|cut -c1-10`
           for ver_dir in $McINC_ROOT/${ft_ver}* ; do
                if [ -d "$ver_dir" ] ; then
                   if [ "$ver_dir" = "$McINC_ROOT/${baseroot}" -a -f "$McINC_ROOT/${baseroot}/src/.make_complete" ]; then
                      echo "$0: ERROR: Compiled version of ${baseroot} already exists"
                      exit 1
                   fi
                      
                   if [ "$ver_dir" != "$McINC_ROOT/$base" -a "$ver_dir" != "$McINC_ROOT/${baseroot}" ]; then
                      case $ver_dir in
                         *inc)
                             #skip this directory since we have to upgrade from a full version
                             # any directory ending in inc, only has pieces
                             continue
                             ;;
                          *)
                             latest_ver=$ver_dir
                             ;;
                      esac
                   fi
                fi
           done

           if [ -z "$latest_ver" ]; then
              echo "$0: ERROR:Must have installed ${ft_ver}xx to use this Fastrack version"
              exit 1
           else
              echo Updating from version $latest_ver
           fi
        fi
     fi
}

#-------
#Make version directory for incremental fasttrack
#-------

make_version_dir()
{
        if [ "$inc_word" = "inc" ]; then
           if [ $act = "make"  -a  ! -f $McINC_ROOT/${baseroot}/.copy_link_complete  ]; then
              old_dir="$latest_ver"
              new_dir="$McINC_ROOT/${baseroot}"
              if [ "$latest_ver" != "$McINC_ROOT/${baseroot}" ] ; then
                 if [ $action = "link" ]; then
                     [ -d $new_dir ] || mkdir $new_dir
                     ( cd $old_dir ;find . -print )|
                     while read file; do
                        # if file is a directory, create it
                        if [ -d ${old_dir}/$file ]; then
                           mkdir ${new_dir}/$file  2>/dev/null
                        else
                           # if file is not a directory, and not a special file link it to the new
                           # directory, or copy it or skip it if it is a special file as indicated below
                           case $file in
                             *copy_link_complete | *make_complete )
                                   # skip this file, indicates all files have been linked in previous version
                                   complete=yes
                                   ;;
                             *.a | *makelog ) 
                                   # copy libraries and makelog
 				   cp -p ${old_dir}/$file $new_dir/$file
                                   ;;
                             *)
                                   # hard link all other files 
                                   rm -f $new_dir/$file
                                   ln ${old_dir}/$file $new_dir/$file 
                                   if [ $? -ne 0 ]; then
                        	      echo "$0: ERROR: Unable to $action ${old_dir}/$file to $new_dir/$file" 
                                      exit 1
                                   fi
                                   ;;
                           esac
                        fi
                     done
                 else
                     #if the copy option is chosen, first verify that the 
                     #new directory does not exist, and  copy all files to new directory

                     rm -rf $McINC_ROOT/${baseroot}
                     cp -pr $latest_ver $McINC_ROOT/${baseroot}  2>/dev/null 
                     if [ $? -ne 0 ]; then
                        echo "$0: ERROR: Unable to $action $latest_ver to $McINC_ROOT/${baseroot} " 
			exit 1
                     fi
                 fi
              fi
   
              (cd $McINC_ROOT/${base};find . -print -type f)| 
              while read file; do
                  [ -d $file ] && [ ! -d $McINC_ROOT/${baseroot}/${file} ] && mkdir ${new_dir}/${file}
                  cmp -s $McINC_ROOT/${base}/$file $McINC_ROOT/${baseroot}/${file} 2>/dev/null
                  if [ $? -ne 0 ]; then
                     rm -f $McINC_ROOT/${baseroot}/$file 2>/dev/null 
                     cp $McINC_ROOT/${base}/$file $McINC_ROOT/${baseroot}/${file} 2>/dev/null
                  fi
              done
   
              # check for files that need to be deleted from the previous distribution
              if [ -f $McINC_ROOT/${base}/del_files ]; then
                  cat -s $McINC_ROOT/${base}/del_files|
                  while read del_file ; do
                     rm -rf $McINC_ROOT/${baseroot}/$del_file
                 done
              fi
              # Create new shell script name if it does not exist
              if [ ! -f $McINC_ROOT/${baseroot}.sh ]; then
                 cp $McINC_ROOT/${base}.sh $McINC_ROOT/${baseroot}.sh
              fi

              # touch file to indicate previous steps are completed
              touch $McINC_ROOT/${baseroot}/.copy_link_complete
           fi
           dir=${baseroot}
        fi
}

#-------
# create a default .mcenv file to be sourced by mcservsh
#-------
make_mcenv()
{
	if [ ! -f $McINC_ROOT/.mcenv ]; then
		cat <<!EOF! > $McINC_ROOT/.mcenv
MCPATH=$McINST_ROOT/data
export MCPATH

PATH=$McINST_ROOT/bin:\$PATH
export PATH
!EOF!
	fi
}

#-------
# print a helpful message about the rest of the install
#-------
help_install()
{
	echo ""
	echo "################################################################################"
	echo ""
	echo "This release of the OpenADDE servers is protected under the GNU Lesser General "
	echo "Public License.  The full text can be found in the file:"
	echo "  $McINST_ROOT/data/lgpl-license.txt"
	echo ""
	echo "To complete installation of the ADDE servers, you must run addeinet.sh as root."
	echo ""
	echo "Datasets are configured in the file:"
	echo "	$McINST_ROOT/data/RESOLV.SRV"
	echo ""
	echo "If you have downloaded the sample data files, RESOLV.SRV will already contain"
	echo "entries which can be uncommented to gain access to the sample data."
	echo ""
	echo "################################################################################"
}

#-------
# set the umask so that the tar file will unpack the way it should
#-------

umask 022

#-------
# record the basename of the script/tarfile/package directory
#-------

base=`basename $0 .sh`

#-------
# parse the undocumented options
#-------

#-------
# make:			default 'make' command
#-------

PATH="`pwd`/${base}/src:$PATH"
export PATH

#-------
# Set compiler defaults
#-------

uname_s=`uname -s`

# Don't build c++ interfaces
# unless explicitly told that cxx compiler works
CXX=
export CXX
F90=
export F90

case $uname_s in
   Linux)
      gcc=true
      CC=gcc
      export CC
      FC=g77
      export FC
      CPPFLAGS=-Df2cFortran
      export CPPFLAGS
      make="make VENDOR=-g77 STRIP=-Wl,-s DEBUG=-O"
      C_COMP=gcc
      unset F_COMP
   ;;
   Darwin)
      gcc=true
      CC=gcc
      export CC
      FC=g77
      export FC
      CPPFLAGS=-Df2cFortran
      export CPPFLAGS
      make="make VENDOR=-g77 STRIP=-Wl,-s DEBUG=-O"
      C_COMP=gcc
      unset F_COMP
      SW_G77=`which g77 |grep "\/sw\/bin\/g77"`
      if [ ! -z "$SW_G77" ]; then
	echo ""
	echo "The first occurence of g77 in your path is /sw/bin/g77.  This version was"
	echo "probably built using the Fink opensource package management system.  McIDAS"
	echo "requires the freely available binary release from http://hpc.sourceforge.net. If"
	echo "you have this version installed, please add the location of the correct binary"
	echo "(usually /usr/local/bin) to the begining of your PATH environment variable by"
	echo "running the following commands:"
	echo ""
	echo "  PATH=/usr/local/bin:\$PATH"
	echo "  export PATH"
	echo ""
	exit 1
      fi
   ;;
   Interix)
      gcc=true
      CC=gcc
      export CC
      FC=g77
      export FC
      CPPFLAGS=-Df2cFortran
      export CPPFLAGS
      make="make VENDOR=-g77 STRIP=-Wl,-s DEBUG=-O"
      C_COMP=gcc
      unset F_COMP
   ;;
   HP-UX)
      make='make VENDOR=-vendor STRIP=-s DEBUG=-O'
      CC=cc
      export CC
      C_COMP=cc
      F_COMP=f77
      CFLAGS='-Aa -D_HPUX_SOURCE +e'
      export CFLAGS
      ver1=`uname -r | sed -e "s/^[A-Z]\.\([0-9]*\)\.[0-9]*$/\1/"`
      ver2=`uname -r | sed -e "s/^[A-Z]\.[0-9]*\.\([0-9]*\)$/\1/"`
      if [ "$ver1" -ge 11 ]; then
	export MCNSL=-lnsl
      fi
      if [ "$ver1" -eq 11 -a "$ver2" -ge 11 ]; then
        F_COMP=f90
      fi
      if [ "$ver1" -gt 11 ]; then
        F_COMP=f90
      fi
   ;;
   SunOS)
      case `uname -p` in
      i386)  # i.e. Solaris x86
        CC=gcc
        export CC
        FC=g77
        export FC
        make="make VENDOR=-g77 STRIP=-Wl,-s DEBUG=-O"
        C_COMP=gcc
        unset F_COMP
        ;;
      *)
        make='make VENDOR=-vendor STRIP=-s DEBUG=-O'
	CC=cc
	export CC
        C_COMP=cc
        F_COMP=f77
        ;;
      esac
   ;;
   IRIX|IRIX64)
      make='make VENDOR=-vendor STRIP=-s DEBUG=-O'
      C_COMP=cc
      F_COMP=f77
      CC=cc
      export CC
   ;;
   AIX)
      make='make VENDOR=-vendor STRIP=-s DEBUG=-O'
      C_COMP=cc
      F_COMP=f77
      CPPFLAGS=-DNDEBUG
      export CPPFLAGS
      CC=cc
      export CC
   ;;
   *)
      make='make VENDOR=-vendor STRIP=-s DEBUG=-O'
      C_COMP=cc
      F_COMP=f77
   ;;
esac

action="link"
no_opt=

for arg in "$@"
do
	case $arg in
	-g)	make='make STRIP= DEBUG=-g'
		echo "$0: BUILDING WITH DEBUG"
		;;
	-v)	make='make VENDOR=-vendor STRIP=-s DEBUG=-O'
		unset CC
		unset FC
		C_COMP=cc
		F_COMP=f77
		case `uname -s` in
		HP-UX)
			CC=cc
			export CC
			ver1=`uname -r | sed -e "s/^[A-Z]\.\([0-9]*\)\.[0-9]*$/\1/"`
			ver2=`uname -r | sed -e "s/^[A-Z]\.[0-9]*\.\([0-9]*\)$/\1/"`
			if [ "$ver1" -ge 11 ]; then
				export MCNSL=-lnsl
			fi
			if [ "$ver1" -eq 11 -a "$ver2" -ge 11 ]; then
				F_COMP=f90
			fi
			if [ "$ver1" -gt 11 ]; then
				F_COMP=f90
			fi
			;;
		SunOS)
			CC=cc
			export CC
			;;
		IRIX|IRIX64)
			CC=cc
			export CC
			;;
		AIX)
			CC=cc
			export CC
			;;
		esac
		;;
	-f90)	FC=f90
		export FC
		F_COMP=f90
		;;
        -gcc) 	CC=gcc
		export CC
		FC=g77
		export FC

		# ld32 on IRIX64 crashes with segmentation violation if you
		# pas the -s strip flag to the linker. Don't strip IRIX code if
		# building with gcc.
		case `uname -s` in
		IRIX|IRIX64)
			make="make VENDOR=-g77 DEBUG=-O"
			;;
		HP-UX)
			make='make VENDOR=-g77 STRIP=-Wl,-s DEBUG=-O'
			ver1=`uname -r | sed -e "s/^[A-Z]\.\([0-9]*\)\.[0-9]*$/\1/"`
			if [ "$ver1" -ge 11 ]; then
				export MCNSL=-lnsl
			fi
			;;
		*)
			make="make VENDOR=-g77 STRIP=-Wl,-s DEBUG=-O"
			;;
		esac
                C_COMP=gcc
		unset F_COMP
		CFLAGS=-DMC_GCC
		export CFLAGS
                echo "$0: Using GNU gcc + g77 compilers"
                ;;
        -f2c) 	CC=gcc
		export CC
		FC=mcfc
		export FC

		# ld32 on IRIX64 crashes with segmentation violation if you
		# pas the -s strip flag to the linker. Don't strip IRIX code if
		# building with gcc.
		case `uname -s` in
		IRIX|IRIX64)
			make="make VENDOR=-f2c DEBUG=-O"
			;;
		HP-UX)
			make='make VENDOR=-f2c DEBUG=-O'
			ver1=`uname -r | sed -e "s/^[A-Z]\.\([0-9]*\)\.[0-9]*$/\1/"`
			if [ "$ver1" -ge 11 ]; then
				export MCNSL=-lnsl
			fi
			;;
		*)
			make="make VENDOR=-f2c STRIP=-Wl,-s DEBUG=-O"
			;;
		esac
                C_COMP=gcc
                unset F_COMP
		CFLAGS=-DMC_F2C
		export CFLAGS
                echo "$0: Using GNU gcc compiler and f2c"
                ;;
        -c)     action="copy"
                ;;
	-noopt)	no_opt=1
		;;
	-*)	echo "$0: ERROR: ILLEGAL ARG $arg"
		exit 1
		;;
	*)	break
		;;
	esac
	shift
done
export C_COMP
export F_COMP

if [ ! -z "$no_opt" ]; then
	make=`echo "$make" | sed -e 's/ DEBUG=-O//'`
	make="$make NOOPT=-noopt"
	echo "$0: Disabling optimizations "
fi

#-------
# check for action
#
# make		- unpack things as necessary, do the make
# install	- install this package (after the make completes)
# uninstall	- uninstall this package (presumably after installing
#		  it)
# unmake	- completely remove the package directory, if there's
#		  a tar file left
#-------

case $1 in
make)
	act=make
	;;
unmake)
	act=unmake
	;;
install)
	act=install
	;;
uninstall)
	act=uninstall
	;;
*)
cat <<EOF
To make, run the command

	sh ./$base.sh make

To install, run the command

	sh ./$base.sh install

To uninstall, run the command

	sh ./$base.sh uninstall

To unmake, run the command

	sh ./$base.sh unmake
EOF
	exit 0
	;;
esac

#-------
# Make sure we are not root.
#-------

ID=`id`

MC_USER=`echo "$ID" |sed -e 's/(/ /g' -e 's/)/ /g' |awk '{print $2}'`
MC_GROUP=`echo "$ID" |sed -e 's/(/ /g' -e 's/)/ /g' |awk '{print $4}'`
export MC_USER
export MC_GROUP

case "$ID" in
'uid=0('*)
	echo "$0: ERROR: cannot run as root"
	exit 1
	;;
esac

#-------
# be paranoid about possibly nuking ourselves with tar
#-------

case $0 in
*.sh)	;;
*)	echo "$0: ERROR: script name must end in .sh to avoid conflicts"
	exit 1
	;;
esac

#-------
# set environment variables for the make
#
# McIDAS_ROOT	- where to find pre-installed stuff:
#	`pwd`/openadde
# McINST_ROOT	- where to install this package
#	`pwd`/openadde
# McINC_ROOT    - where to look for incremental upgrade candidates
#	`pwd`
#
# We need to check for whether the mcidas home directory exists, and
# whether we are installing in the mcidas account or somewhere else.
#-------

McIDAS_ROOT=`pwd`/openadde
McINST_ROOT=`pwd`/openadde
McINC_ROOT=`pwd`

export McIDAS_ROOT
export McINST_ROOT
export McINC_ROOT

#-------
# check for required directories
#-------
check_version

#-------
# if doing a make check if compilers are present
#-------

if [ "$act" = "make" ]; then
   #check for C compiler
   if [ -n "${C_COMP}" ]; then
      type ${C_COMP} >/dev/null 2>&1
      if [ $? -ne 0 ]; then
 	 echo "$0: ERROR: ${C_COMP} compiler not found in PATH"
	 exit 1
      fi
   fi
   #check for fortran compiler
   if [ -n "${F_COMP}" ]; then
      type ${F_COMP} >/dev/null 2>&1
      if [ $? -ne 0 ]; then
 	 echo "$0: ERROR: ${F_COMP} compiler not found in PATH"
	 exit 1
      fi
   fi
   #check for X11
   if [ ! -d "/usr/X11R6" -a ! -d "/usr/lib/X11" ]; then
      echo "$0: WARNING: could not locate X11.  Continue [y/n]?"
        read CONTYN
        case $CONTYN
        in
        y*)
                ;;
        *)      exit 1
                ;;
        esac
   fi
fi

#-------
# Check that $McINST_ROOT directories are okay, and create
# them if necessary.
#-------

exit=0
dir_list="	$McINST_ROOT \
		$McINST_ROOT/bin \
		$McINST_ROOT/data \
		$McINST_ROOT/lib \
		$McINST_ROOT/src \
		$McINST_ROOT/man \
		$McINST_ROOT/man/man3"

for v in	$dir_list
do
	if	[ ! -d "$v" ]
	then	echo "$0: making directory $v"
		if	mkdir $v
		then	:
		else	echo "$0: ERROR in making directory $v"
			exit=1
		fi
	fi
done
case $exit in
1)	echo "$0: Cannot make required directories."
	exit $exit
	;;
esac

#-------
# Check that $McIDAS_ROOT directories are okay, and bail out
# if they don't exist.
#
# Note that we put this test after the directory-making part above, in
# case we are setting up a mcidas account for the first time, or in
# case we are setting up a personal account on a machine that doesn't
# have mcidas installed.  In either case the above section would have
# created the directories checked for below.
#-------

dir_list="	$McINST_ROOT \
		$McINST_ROOT/bin \
		$McINST_ROOT/lib"

for v in	$dir_list
do
	if	[ ! -d "$v" ]
	then	echo "$0: WARNING: account lacks directory $v"
	fi
done

#-------
# havetar - nonempty if we have a tar file for this package
# tarcmd - the command to use to unpack the tar file
#
# They are either both empty, or both nonempty.
#-------

tarcmd=
havetar=
tarfile=$base.tar
tarzfile=$base.tar.Z

if	[ -f "$tarfile" ]; then
	tarcmd="tar xf $tarfile"
	havetar=$tarfile
elif	[ -f "$tarzfile" ]; then
	if [ ! $uname_s = "Interix" ]; then
		tarcmd="zcat < $tarzfile | tar xf -"
	else
		tarcmd="tar -xzf $tarzfile"
	fi
	havetar=$tarzfile
fi

#-------
# dir - the root directory of the package distribution
#
# If it doesn't exist, try to create it using the tar file.
# If we don't have a tar file, we're stuck.
#-------

dir=$base

if	[ ! -d "$dir" ]
then
	case $havetar in
	'')	echo "$0: ERROR: cannot find '$tarfile' or '$tarzfile'"
		exit 1
		;;
	esac

	if	[ ! -w . ]
	then	echo "$0: ERROR: no permission to write into the current directory"
		exit 1
	fi

	echo "$0: unpacking $havetar"

	eval $tarcmd

	if	[ ! -d "$dir" ]
	then	echo "$0: ERROR: cannot unpack tar file!"
		exit 1
	fi
fi

make_version_dir

# By here, we must have the directory, or we can't go on.

if	[ ! -d "$dir" ]
then	echo "$0: ERROR: cannot find package directory!"
	exit 1
fi

#-------
# srcdir - the source directory of the package distribution
# This is where the top-level makefile lives.
#-------

havemake=
for srcdir in	$dir $dir/src
do
	if	[ -f "$srcdir/makefile" -o -f "$srcdir/Makefile" ]
	then	havemake=true
		break
	fi
done
case $havemake in
'')	echo "$0: ERROR: package lacks a makefile!"
	exit 1
	;;
esac
if	[ ! -d "$srcdir" ]
then	echo "$0: ERROR: cannot find source directory!"
	exit 1
fi

# record current directory, just in case
pwd=`pwd`

# cd to the source directory

if	cd $srcdir
then	:
else	echo "$0: ERROR: cannot cd to '$srcdir'"
	exit 1
fi

case $act
in
make)
	# Do the build.

	# The 'make clean' removes intermediate generated files
	# that we don't need in order to do the install.
	# This is to save space.

	if	eval $make
	then	:
	else	echo "$0: ERROR: 'make' failed"
		exit 1
	fi

	if	eval $make -n clean
	then	:
	else	echo "$0: ERROR: 'make clean' failed"
		exit 1
	fi

	# If we get to here everything is fine.

        touch ${McINC_ROOT}/${srcdir}/.make_complete
	echo
	echo "$0: make completed normally."
	echo
	;;
unmake)
	# Undo the build.

	if	eval $make clobber
	then	:
	else	echo "$0: ERROR: 'make clobber' failed"
		exit 1
	fi

	if	cd $pwd
	then	:
	else	echo "ERROR: cannot cd to '$pwd'"
		exit 1
	fi

	case $havetar in
	?*)	if	rm -rf $dir
		then	:
		else	echo "$0: ERROR: 'rm -rf $dir' failed"
			exit 1
		fi
                if [ "$inc_word" = "inc" ]; then
	           if	rm -rf $base
		   then	:
		   else	echo "$0: ERROR: 'rm -rf $base' failed"
			   exit 1
		   fi
                fi
		;;
	*)	echo
		echo "$0: WARNING: no tar file, so not removing $dir"
		;;
	esac

	# If we get to here everything is fine.

	echo
	echo "$0: unmake completed normally."
	echo
	;;
install)
	# Do the install.

	if	eval $make install.all
	then	:
	else	echo "$0: ERROR: 'make install.all' failed"
		exit 1
	fi

	make_mcenv

	help_install

	# If we get to here everything is fine.

	echo
	echo "$0: install completed normally."
	echo
	;;
uninstall)
	# Do the uninstall.

	if	eval $make uninstall.all
	then	:
	else	echo "$0: ERROR: 'make uninstall.all' failed"
		exit 1
	fi

	# If we get to here everything is fine.

	echo
	echo "$0: uninstall completed normally."
	echo
	;;
esac

exit 0
######################################################################

