#!/bin/sh
# @(#)install.sh	19.1 (ESO-IPG) 02/25/03 14:31:59
#
#  Installation script for MIDAS from CD-ROM with binaries.
#
#set -x

###########################################################################
#
#  Initialize all the read-only variables used by this script.  Mark
#  them readonly so they don't get accidentally modified
#
###########################################################################

# Determine how to set prompt
if [ "`echo -n a`" = a ]; then
	# BSD echo
	NNN=-n 
	CCC=        
else
	# USG echo
	NNN= 
	CCC='\c'      
fi
readonly NNN CCC

# Most of this needs to updated for each new CD.
MIDAS_SOURCES="95novpl2.0.tar.z"
MIDVERS="95NOV"
DATE='February 1996'
COPYDATE="1996"
RELEASE="95NOVpl2.0"

RETURN_MSG="RETURN TO MAIN MENU"

readonly MIDAS_SOURCES MIDVERS DATE COPYDATE RETURN_MSG RELEASE

STATE_CD=1
STATE_ARCH=2
STATE_MIDASHOME=3
STATE_PROD_SELECT=4
STATE_INSTALL=5
STATE_SETUP=6
STATE_QUIT=Q

readonly STATE_CD STATE_ARCH STATE_MIDASHOME STATE_PROD_SELECT 
readonly STATE_INSTALL STATE_QUIT STATE_SETUP

PROD_BIN="MIDAS binary"
PROD_SRC="MIDAS sources"
PROD_GUI="MIDAS statically-linked GUIs"
PROD_DEMO="MIDAS demo data"
PROD_CALIB="MIDAS calibration data"

readonly PROD_BIN PROD_SRC PROD_GUI PROD_DEMO PROD_CALIB

ARCH_ALPHA="Alpha OSF"
ARCH_HP700="HP9000 Series 700/800"
ARCH_IBM="IBM RS6000 AIX"
ARCH_SGI5="SGI IRIX 5"
ARCH_SUNOS="SPARC Sunos 4.1.x"
ARCH_SOLARIS="SPARC Solaris 5.x"
ARCH_LINUX="PC LINUX 1.2.13"

REL_ALPHA="OSF1"
REL_HP700="HP-UX"
REL_IBM="AIX"
REL_SGI5="IRIX"
REL_SUNOS="SunOS_4.1.3"
REL_SOLARIS4="SunOS_5.4"
REL_SOLARIS5="SunOS_5.5"
REL_LINUX="Linux"

readonly ARCH_ALPHA ARCH_HP700 ARCH_IBM 
readonly ARCH_SGI5 ARCH_SUNOS ARCH_SOLARIS ARCH_LINUX
readonly REL_ALPHA REL_HP700 REL_IBM 
readonly REL_SGI5 REL_SUNOS REL_SOLARIS4 REL_SOLARIS5 REL_LINUX

ARCH_LIST="$ARCH_ALPHA,$ARCH_HP700,$ARCH_IBM"
ARCH_LIST="$ARCH_LIST,$ARCH_SGI5,$ARCH_SUNOS,$ARCH_SOLARIS,$ARCH_LINUX"

readonly ARCH_LIST

# Script sets these up during run (all begin with _)
MIDAS_CDDIR=
MIDAS_ARCH=
MIDAS_PROD_LIST=
MIDAS_PROD_SELECTED=
MIDAS_PROD_INSTALLED=
MIDAS_STATE=
MIDAS_SETUP=
MIDAS_BINDIR_DONE=
MIDAS_LIBDIR_DONE=
MIDAS_MANDIR_DONE=
MIDAS_ARCH_PREFIX=
MIDAS_MANDIR=/usr/man/manl
MIDAS_BINDIR=/usr/bin
MIDAS_LIBDIR=/usr/lib
MIDAS_SHID=3.1
#######################################################################
#
#  Generic support routines
#
#######################################################################

aborted()
{
	#  Catch user-generated interrupts, and quit

	echo ""
	echo "**** INSTALLATION ABORTED BY USER ****"
	echo ""
	exit 1
}
trap aborted 1 2 3

killed()
{
	#  Catch attempts to kill this process

    echo ""
    echo "**** INSTALLATION ABORTED ABNORMALLY ****"
    echo ""
    exit 1
}
trap killed 15

error()
{
	#  standard error message

	echo '***' $* > /dev/tty
	false
}

fatal_error()
{
	#  Print error message and die; this should never happen

	error $*
	kill -15 $$
}

change_ifs()
{
	#
	#  Change IFS to $1, saving previous value in $OFS.
	#  NOTE: this is not a stack!!  Do not nest calls!!

	if [ "$IFS" != "$1" ]; then
		OIFS="$IFS"
		IFS="$1"
	fi
}

restore_ifs()
{
	#  Restore the old value of IFS

	IFS="$OIFS"
}

array()
{
	#
	#  mimic the behavior of arrays; pick the $2'th element out of $1
	#  uses 1-indexing
	#

	vector="$1"
	rindex="$2"

	index=1
	change_ifs ","
	for elt in $vector; do
		if [ "$index" -eq "$rindex" ]; then
			echo "$elt"
			restore_ifs
			return
		fi
		index=`expr $index + 1`
	done

	restore_ifs
	fatal_error "Array selection failed for $vector[$rindex]"
}

necho()
{
	#
	#  A safe way to perform echo without sending a new-line
	#

	echo $NNN "$*" $CCC > /dev/tty
}

ask_return()
{
	#  Simply get the user to hit the return key

	necho 'Hit <return> to continue ...'
	read x
}

ask_yn()
{
	#
	#  Get a yes/no answer from the user; $1 is the prompt, $2 the default
	#

	prompt="$1"
	def="${2:-y}"		# yes is the default if not supplied
	while true; do
		necho "$prompt [$def]: "
		read answer
		answer="${answer:-$def}"
		case "$answer" in
			[yY])
				answer=y
				break
				;;
			[nN])
				answer=n
				break
				;;
			  *)
				error Please enter "'y'" or "'n'".
				;;
		esac
	done
	[ $answer = y ]
}

ask_response()
{
	#
	#  Get a (non-zero) response from the user
	#  $1 is the question, $2 is the default (if any).
	#

	question="$1"
	default="$2"
	while true; do
		if [ -z "$default" ]; then
			necho "$question: "
		else
			necho "$question [$default]: "
		fi
		read answer
		if [ -z "$answer" ]; then
			answer=$default
		fi
		if [ -z "$answer" ]; then
			error Please enter a non-empty string.
		else
			break
		fi
	done
	echo $answer
}

difference()
{
	#
	#  Calculate and return the list of all elements in $1, but not
	#  in $2.  This calculates set difference the hard way.
	#

	l1="$1" 
	l2="$2"
	l3=

	change_ifs ","
	for i in $l1; do
		if in_list "$l2" "$i"; then
			echo > /dev/null		# do nothing
		else
			l3=`addto "$l3" "$i"`
		fi
	done
	restore_ifs

	echo "$l3"
}

addto()
{
	#
	#  Add element $2 to list $1; return the result
	#

	ll="$1"
	el="$2"

	change_ifs ","
	if in_list "$ll" "$el"; then
		echo > /dev/null		# do nothing
	else
		if [ -z "$ll" ]; then
			ll="$el"
		else
			ll="$ll,$el"
		fi
	fi
	restore_ifs

	echo "$ll"
}

genlist()
{
	#  generate a list of numbers from $1..$2

	echo $1 $2 | awk '{
		for (i=$1; i<=$2; i++) list=list "," i
		print substr(list,2)
	}'
}

count()
{
	#  count the number of entries in $1

	echo $1 | awk -F, '{ print NF }'
}

in_list()
{
	#
	#  Determine whether $2 is in the list $1; $1 is a comma-separated
	#  list of valid values
	#

	found=f
	list="$1"
	arg="$2"
	change_ifs ","
	for i in $list
	do
		if [ "$i" = "$arg" ]; then
			found=t
			break
		fi
	done

	restore_ifs
	[ $found = t ]
}

ask_list()
{
	# 
	#  Ask the user for a value in list $2; the prompt is $1, and
	#  the default value is $3
	#

	prompt="$1"
	default="$3"
	list="$2"

	while true; do
		num=`ask_response "$prompt" "$default"`
		if in_list "$list" $num; then
			break
		else
			error "$num is not one of the choices."
		fi
	done

	echo $num
}

ask_multi()
{
	#
	#  Allow a multiple selection, by number.  $1 is the prompt
	#  to use, $2 is the list of valid inputs
	#

	prompt="$1"
	list="$2"

	while true; do
		pselect=`ask_response "$prompt"`
		err=f
		change_ifs ","
		for num in $pselect; do
			if in_list "$list" $num; then
				true
			else
				error "$num is not a valid choice"
				err=t
				break
			fi
		done
		restore_ifs
		if [ "$err" != "t" ]; then
			break
		fi
	done
	echo $pselect
}

valid_dir()
{
	#  Determine if $1 is a valid directory specification
	#  This means it must begin with a '/'

	if [ "`expr "$1" : '\(/\).*'`" != "/" ]; then
		error "Directory name must begin with a '/'"
	fi

	return $?
}

exists_dir()
{
	#  Determine whether directory $1 exists.  It must also
	#  be a valid directory (see above).

	dname=$1

	if [ -d "$dname" ]; then
		valid_dir $dname
	else
		error "Directory \"$dname\" does not exist"
	fi
	return $?
}

#######################################################################
#
#  Pre- and Post- installation banners
#
#######################################################################

banner()
{
#  Banner before the script begins.  Put trademarks, disclaimers,
#  etc. in here.

clear > /dev/tty
echo "                                                                    " > /dev/tty
echo "     ********************************************************************" > /dev/tty
echo "                       $RELEASE release of ESO-MIDAS " > /dev/tty
echo "               Copyright (C) $COPYDATE European Southern Observatory" > /dev/tty
echo "     This program is free software; you can redistribute it and/or modify" > /dev/tty
echo "     it under the terms of the GNU General Public License as published by" > /dev/tty
echo "     the Free Software Foundation; either version 2 of the License, or   " > /dev/tty
echo "     (at your option) any later version.                                 " > /dev/tty
echo "                                                                      " > /dev/tty
echo "     This program is distributed in the hope that it will be useful, but " > /dev/tty
echo "     WITHOUT ANY WARRANTY; without even the implied warranty of          " > /dev/tty
echo "     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU    " > /dev/tty
echo "     General Public License for more details.                            " > /dev/tty
echo "                                                                      " > /dev/tty
echo "     You should have received a copy of the GNU General Public License   " > /dev/tty
echo "     along with this program; if not, write to the Free Software         " > /dev/tty
echo "     Foundation,  Inc., 675 Massachusetss Ave, Cambridge, MA 02139, USA. " > /dev/tty
echo "     Corresponding concerning ESO-MIDAS should be addressed as follows:  " > /dev/tty
echo "     Internet e-mail: midas@eso.org                                      " > /dev/tty
echo "     Postal address: European Southern Observatory                       " > /dev/tty
echo "                     Data Management Division                            " > /dev/tty
echo "                     Karl-Schwarzschild-Strasse 2                        " > /dev/tty
echo "                     D-85748 Garching bei Muenchen. GERMANY              " > /dev/tty
echo "     ********************************************************************" > /dev/tty
}

banner1()
{
#  Banner before completing MIDAS installation
  clear > /dev/tty
#  echo "" > /dev/tty
  echo "  Complete the ESO-MIDAS installation means:" > /dev/tty
  echo "" > /dev/tty
  echo "  1. Create a soft link from /midas to $MIDASHOME" >/dev/tty
  echo "  2. Copy the inmidas, gomidas and helpmidas scripts from" > /dev/tty
  echo "     $MIDASHOME/$MIDVERS/system/unix to e.g.: /usr/bin" > /dev/tty
  echo "  3. Copy inmidas.l, gomidas.l and helpmidas.l man-pages from" > /dev/tty 
  echo "     $MIDASHOME/$MIDVERS/system/unix/manl to e.g. /usr/man/manl" >/dev/tty
  echo "  4. Create the system references to MIDAS shared libraries located in" >/dev/tty
  echo "       $MIDASHOME/$MIDVERS/lib" >/dev/tty
  echo "" > /dev/tty
  echo "  If you can not become superuser to run these tasks you can, as a normal" > /dev/tty 
  echo "  user, run MIDAS by setting the following environment variables and" > /dev/tty
  echo "  executing the inmidas, gomidas and helpmidas scripts located in" > /dev/tty  
  echo "  $MIDASHOME/$MIDVERS/system/unix" > /dev/tty
  echo "" >/dev/tty
  echo "    % setenv MIDASHOME $MIDASHOME" >/dev/tty
  case "$MIDAS_ARCH" in
    $ARCH_HP700)
      echo "    % setenv SHLIB_PATH $MIDASHOME/$MIDVERS/lib" >/dev/tty
      ;;
    *)
      echo "    % setenv LD_LIBRARY_PATH $MIDASHOME/$MIDVERS/lib" >/dev/tty
      ;;
    esac
  echo "    % $MIDASHOME/$MIDVERS/system/unix/inmidas" > /dev/tty
  echo "" >/dev/tty
}

post_install()
{
	# Should do something here??

	echo "                                                                " > /dev/tty
	echo "                                                                " > /dev/tty
}

#######################################################################
#
#  State Querying Functions
#     - isset_*        : only returns status
#     - check_*        : calls isset_* and print message
#     - precond_       : checks if preconditions are met
#     - check_precond_ : checks preconditions, prints message
#
#######################################################################
isset_su()
{
	if  user=`sh -c whoami 2>/dev/null` ; then
		:
	elif  user=`sh -c /usr/bin/whoami 2>/dev/null` ; then
		:
	elif  user=`sh -c /usr/ucb/whoami 2>/dev/null` ; then
		:
	else
		user="$USER"
	fi
	[ "$user" = "root" ]
}

isset_cddir()
{
	[ -n "$MIDAS_CDDIR" ]
}

isset_arch()
{
	[ -n "$MIDAS_ARCH" ]
}

isset_midashome()
{
	[ -n "$MIDASHOME" -a -d "$MIDASHOME" ]
}

isset_product()
{
	[ -n "$MIDAS_PROD_SELECTED" ]
}

isset_prod_installed()
{
	[ -n "$MIDAS_PROD_INSTALLED" ]
}

isset_setup()
{
	[ -f "$MIDASHOME/$MIDVERS/monit/prepa.exe" ]
}

isset_setup_installed()
{
	[ -n "$MIDAS_SETUP" ]
}

#
#  Check functions
#

check_cddir()
{
	isset_cddir ||
		( error "Please enter the CD mount point first (item $STATE_CD)."; 
		  ask_return;
		  false
		)
}

check_arch()
{
	isset_arch ||
		( error "Please select an architecture first (item $STATE_ARCH).";
		  ask_return;
		  false
		)
}

check_setup()
{
	isset_setup ||
		( error "MIDAS binary must be installed first (item $STATE_PROD_SELECT and/or item $STATE_INSTALL)."; 
		  ask_return;
		  false
		)
}

check_midashome()
{
	isset_midashome ||
		( error "Please select the installation directory MIDASHOME first (item $STATE_MIDASHOME).";
		  ask_return;
		  false
		)
}

check_product()
{
	isset_product ||
		( error "Please select the ESO-MIDAS product(s) to install first (item $STATE_PROD_SELECT).";
		  ask_return;
		  false
		)
}

check_prod_installed()
{
	isset_prod_installed || 
		( error "Please install the ESO-MIDAS products first (item $STATE_INSTALL).";
		  ask_return;
		  false
		)
}

#
#  Precondition functions
#

precond_product()
{
	isset_arch && isset_midashome
}

precond_install()
{
	isset_cddir && isset_arch && isset_midashome && isset_product
}

precond_setup()
{
	isset_midashome && isset_product && isset_arch && isset_prod_installed
}

precond_run_password()
{
	isset_midashome && isset_password
}

#
#  Check Precondition functions
#
check_precond_run_password()
{
	check_cddir && check_midashome 
}

check_precond_product()
{
	check_arch && check_midashome
}

check_precond_install()
{
	check_cddir && check_arch && check_midashome && check_product
}

check_precond_setup()
{
	check_midashome && check_arch && check_setup
}

######################################################################
#
#  State setting and querying functions
#
######################################################################

set_state()
{
	#  
	#  Sanity check the state; find the lowest state whose preconditions
	#  are met, and which has not been completed.  Break after two passes.

	pass=1
	while true; do
		case "$MIDAS_STATE" in
			$STATE_CD)
				if isset_cddir; then
					MIDAS_STATE=`expr $MIDAS_STATE + 1`
					continue
				else
					break
				fi
				;;
			$STATE_ARCH)
				if isset_arch; then
					MIDAS_STATE=`expr $MIDAS_STATE + 1`
					continue
				else
					break
				fi
				;;
			$STATE_MIDASHOME)
				if isset_midashome; then
					MIDAS_STATE=`expr $MIDAS_STATE + 1`
					continue
				else
					break
				fi
				;;
			$STATE_PROD_SELECT)
				if precond_product; then
					if isset_product || isset_prod_installed; then
						MIDAS_STATE=`expr $MIDAS_STATE + 1`
						continue
					fi
					break
				fi
				;;
			$STATE_INSTALL)
				if precond_install; then
					break
				elif isset_prod_installed; then
					MIDAS_STATE=`expr $MIDAS_STATE + 1`
					continue
				fi
				;;
			$STATE_SETUP)
				if precond_setup; then
					break
				fi
				;;
			$STATE_QUIT)
				break
				;;
		esac
		if [ "$pass" -gt 1 ]; then
			break
		fi

		pass=`expr $pass + 1`
		MIDAS_STATE=1
	done
}

show_state()
{
	#  Display the current state.  Prints just about everything the user
	#  needs to know about the installation process.

	if isset_cddir || isset_arch || isset_midashome; then
		# one of these must be set for anything to be displayed
		echo > /dev/null
	else
		return
	fi

	echo '***************************************************************************' > /dev/tty
		echo "  ESO-MIDAS Release MIDVERS:           $MIDVERS"       > /dev/tty
	if isset_cddir; then
		echo "  CD mount directory:                  $MIDAS_CDDIR" > /dev/tty
	fi
	if isset_arch; then
		echo "  Target Architecture:                 $MIDAS_ARCH" > /dev/tty
	fi
	if isset_midashome; then
		echo "  Installation Directory MIDASHOME:    $MIDASHOME"       > /dev/tty
	fi
	if isset_product; then
		echo "  Products selected for installation:   "       > /dev/tty
		ctr=1
		change_ifs ","
		for i in $MIDAS_PROD_SELECTED; do
			echo "              ${ctr}. ${i}.         " > /dev/tty
			ctr=`expr $ctr + 1`
		done
		restore_ifs
	fi
	if isset_prod_installed; then
		echo "  Products installed:   "       > /dev/tty
		ctr=1
		change_ifs ","
		for i in $MIDAS_PROD_INSTALLED; do
			echo "              ${ctr}. ${i}.         " > /dev/tty
			ctr=`expr $ctr + 1`
		done
		restore_ifs
	fi
	echo '***************************************************************************' > /dev/tty
}

#######################################################################
#
#  Main Action Routines
#
#######################################################################

build_prodlist()
{
	#
	#  Build a list of products supported on chosen architecture
	#

	MIDAS_PROD_LIST="$PROD_SRC"
	case "$MIDAS_ARCH" in
		$ARCH_SUNOS|$ARCH_LINUX)
		    if [ -n "$MIDAS_PROD_LIST" ]; then
			MIDAS_PROD_LIST="$MIDAS_PROD_LIST,$PROD_BIN,$PROD_GUI,$PROD_DEMO,$PROD_CALIB"
		    else
			MIDAS_PROD_LIST="$PROD_BIN,$PROD_GUI,$PROD_DEMO,$PROD_CALIB"
		    fi
			;;
		$ARCH_HP700|$ARCH_SOLARIS|$ARCH_ALPHA|$ARCH_SGI5|$ARCH_IBM)
		    if [ -n "$MIDAS_PROD_LIST" ]; then
			MIDAS_PROD_LIST="$MIDAS_PROD_LIST,$PROD_BIN,$PROD_DEMO,$PROD_CALIB"
		    else
			MIDAS_PROD_LIST="$PROD_BIN,$PROD_DEMO,$PROD_CALIB"
		    fi
			;;
		*)
			fatal_error "Unknown architecture $MIDAS_ARCH"
			;;
	esac
}

pick_cddir()
{
	#
	#  Allow the user to specify the directory on which the CD
	#  is mounted.  Usually this is /cdrom.
	#

	clear > /dev/tty

	echo "                                                       " > /dev/tty
	echo "  This installation program must know where the MIDAS  " > /dev/tty
	echo "  CD has been mounted. The usual mount point is /cdrom." > /dev/tty
	echo "                                                       " > /dev/tty
	echo "  Type in 'R' at the prompt below if you want to return" > /dev/tty
	echo "  to the main menu. " > /dev/tty
	echo "                                                       " > /dev/tty

	while true; do
		cd_def=${MIDAS_CDDIR:-/cdrom}
		dir=`ask_response 'Enter the CD mount point' $cd_def`
		if [ "$dir" = "r" -o "$dir" = "R" ]; then
			break
		elif exists_dir "$dir"; then
			ifile=`ls $dir|grep -i install.sh`
			if [ -z "$ifile" ]; then
				error "This directory does not contain any MIDAS products."
			else
				MIDAS_CDDIR=$dir
				break
			fi
		fi
	done

	isset_cddir
}

pick_arch()
{
	#
	#  Select an architecture/toolkit combination
	#

	clear > /dev/tty

	echo "                                          " 	> /dev/tty
	echo "Please select one of the following," > /dev/tty
	echo "or type 'R' to return to the main menu." > /dev/tty
	echo "                                          " 	> /dev/tty
	echo "Architecture" | awk '{ printf("     %-25s\n", $1) }'  > /dev/tty
	echo "============" | awk '{ printf("     %-25s\n", $1) }'  > /dev/tty
	ctr=1
	change_ifs ","
	for i in $ARCH_LIST; do
		arch="$i"
		echo "${ctr}.:${arch}" 
		ctr=`expr $ctr + 1`
	done | awk -F: '{ printf(" %3s %-25s\n", $1, $2) }' > /dev/tty
	echo "  R. $RETURN_MSG." > /dev/tty
	echo "                 " > /dev/tty
	restore_ifs

	# For some reason, ctr=1 after the above for loop; 
	# The pipe seems to cause this
	ctr=`count "$ARCH_LIST"`
	alist=`genlist 1 $ctr`
	alist="$alist,r,R"

	aselect=`ask_list 'Enter your selection' "$alist"`
	case "$aselect" in
		[rR])	;;
		   *)	MIDAS_ARCH=`array "$ARCH_LIST" "$aselect"`
				MIDAS_PROD_SELECTED=""
				MIDAS_PROD_INSTALLED=""
                        case "$MIDAS_ARCH" in
                                $ARCH_ALPHA)    MIDAS_ARCH_PREFIX=alphaosf;;
                                $ARCH_HP700)    MIDAS_ARCH_PREFIX=hp700;;
                                $ARCH_IBM)      MIDAS_ARCH_PREFIX=rs6000;;
                                $ARCH_SGI5)     MIDAS_ARCH_PREFIX=sgirix5;;
                                $ARCH_SUNOS)    MIDAS_ARCH_PREFIX=sparcsun;;
                                $ARCH_SOLARIS)  MIDAS_ARCH_PREFIX=sparcsol;;
                                $ARCH_LINUX)    MIDAS_ARCH_PREFIX=pclinux;;
			esac
				;;
	esac

	isset_arch
}

pick_midashome()
{
	#
	#  Pick the MIDASHOME directory; this is inherited from the environment,
	#  if already set.
	#

	clear > /dev/tty

	echo "                                                           " > /dev/tty
	echo "  All  ESO-MIDAS products  for  the same  architecture     " > /dev/tty
	echo "  are installed in the same directory.  The location of    " > /dev/tty
	echo "  this directory is stored in the environment variable     " > /dev/tty
	echo "  MIDASHOME. You will need to designate the location of    " > /dev/tty
	echo "  this directory, and possibly create it before you can     " > /dev/tty
	echo "  install any ESO-MIDAS products.                                  " > /dev/tty
	echo "                                                           " > /dev/tty
	echo "  Type in 'R' at the prompt below if you want to return    " > /dev/tty
	echo "  to the main menu. " > /dev/tty

	while true; do
		echo "                                                           " > /dev/tty
		echo 'Enter the name of the directory in which to install ESO-MIDAS products.' > /dev/tty
		dir=`ask_response 'MIDASHOME' $MIDASHOME`
		if [ "$dir" = "r" -o "$dir" = "R" ]; then
			break
		else
			if valid_dir "$dir"; then
				if [ ! -d "$dir" ]; then
					echo "Directory $dir does not exist. " > /dev/tty
					if ask_yn "OK to create new directory $dir"; then
						mkdir $dir
						if [ $? -ne 0 ]; then
							error "Unable to create directory $dir."
							continue
						fi
					else
						continue
					fi
				fi
				if ask_yn "OK to install in directory $dir"; then
					MIDASHOME=$dir
					export MIDASHOME
					break
				fi
			fi
		fi
	done

	isset_midashome
}

pick_mandir()
{
  echo "                                                                        " > /dev/tty
  echo "Enter the name of the directory in which to install ESO-MIDAS man-pages," > /dev/tty
  echo "or type in 'R' at the prompt below if you want to skip                  " > /dev/tty 
  echo "                                                                        " > /dev/tty
  while true; do
    dir=`ask_response 'MIDAS_MANDIR' $MIDAS_MANDIR`
      if [ "$dir" = "r" -o "$dir" = "R" ]; then
	break
      else
	if valid_dir "$dir"; then
	  if [ ! -d "$dir" ]; then
	    echo "Directory $dir does not exist. " > /dev/tty
	    continue
	  fi
	if ask_yn "OK to copy ESO-MIDAS man-pages in directory $dir"; then
	  man_suffix=`expr "$dir" : '.*man\(.\)'`
	  for manpage in inmidas gomidas helpmidas readline
	  do 
	    cp $MIDASHOME/$MIDVERS/system/unix/manl/$manpage.l $dir/$manpage.$man_suffix
	    echo "cp $MIDASHOME/$MIDVERS/system/unix/manl/$manpage.l $dir/$manpage.$man_suffix" >/dev/tty
	  done
	  MIDAS_MANDIR_DONE="yes"
	  break
	fi
      fi
    fi
  done
}

pick_bindir()
{
  echo "                                                                      " > /dev/tty
  echo "Enter the name of the directory in which to install ESO-MIDAS scripts," > /dev/tty
  echo "or type in 'R' at the prompt below if you want to skip                " > /dev/tty 
  echo "                                                                      " > /dev/tty
  while true; do
    dir=`ask_response 'MIDAS_BINDIR' $MIDAS_BINDIR`
    if [ "$dir" = "r" -o "$dir" = "R" ]; then
      break
    else
      if valid_dir "$dir"; then
	if [ ! -d "$dir" ]; then
          echo "Directory $dir does not exist. " > /dev/tty
	    continue
	fi
	if ask_yn "OK to copy ESO-MIDAS scripts in directory $dir"; then
	  MIDASHOME_0=`echo MIDASHOME0=$MIDASHOME | sed 's/\//\\\\\//g'`
	  MIDVERS_0=`echo MIDVERS0=$MIDVERS`
 	  for script in inmidas gomidas helpmidas
	  do 
	    cp $MIDASHOME/$MIDVERS/system/unix/$script $dir
	    echo "cp $MIDASHOME/$MIDVERS/system/unix/$script $dir" >/dev/tty
	  done
	  for file in $dir/inmidas $dir/helpmidas
	  do
	    echo "Editing $file ..."
	    cat $file | sed  \
              -e 's/^MIDASHOME0=.*/'$MIDASHOME_0'/' \
              -e 's/^MIDVERS0=.*/'$MIDVERS_0'/' \
              > $file.t
	    chmod +xr $file.t
	    mv -f $file.t $file
	  done
	  MIDAS_BINDIR_DONE="yes"
	  break
        fi
      fi
    fi
  done
}

pick_libdir()
{
  echo "                                                                      " > /dev/tty
  echo "Enter the name of the directory in which to install ESO-MIDAS libraries," > /dev/tty
  echo "or type in 'R' at the prompt below if you want to skip                " > /dev/tty 
  echo "                                                                      " > /dev/tty
  while true; do
    dir=`ask_response 'MIDAS_LIBDIR' $MIDAS_LIBDIR`
    if [ "$dir" = "r" -o "$dir" = "R" ]; then
      break
    else
      if valid_dir "$dir"; then
	if [ ! -d "$dir" ]; then
          echo "Directory $dir does not exist. " > /dev/tty
	    continue
	fi
	if ask_yn "OK to link ESO-MIDAS libraries in directory $dir"; then
 	  for library in libmidas libgmidas
	  do 
	    case "$MIDAS_ARCH" in
		$ARCH_ALPHA|$ARCH_SOLARIS)
		  rm -f $dir/$library.so
		  ln -s $MIDASHOME/$MIDVERS/lib/$library.so $dir/$library.so
		  echo "ln -s $MIDASHOME/$MIDVERS/$library.so $dir/$library.so" >/dev/tty
		  ;;
		$ARCH_SUNOS)
		  rm -f $dir/$library.so.$MIDAS_SHID
		  ln -s $MIDASHOME/$MIDVERS/lib/$library.so.$MIDAS_SHID $dir/$library.so.$MIDAS_SHID
		  echo "ln -s $MIDASHOME/$MIDVERS/lib/$library.so.$MIDAS_SHID $dir/$library.so.$MIDAS_SHID" >/dev/tty
		  /usr/etc/ldconfig
		  ;;
		*)
		  error "No ESO-MIDAS shared libraries expected for $MIDAS_ARCH"
		  return
		  ;;
            esac
	  done
	  MIDAS_LIBDIR_DONE="yes"
	  break
        fi
      fi
    fi
  done
}

pick_product()
{
	#
	#  Pick the list of products to install, based on the architecture
	#

	if check_precond_product; then
		clear > /dev/tty

		build_prodlist

		echo "                                            "  > /dev/tty
		echo "Please select any of the following products."  > /dev/tty
		echo "If you want to install more than one product," > /dev/tty
		echo "enter them in a comma-separated list."		 > /dev/tty
		echo "                                            "  > /dev/tty

		ctr=1
		plist=
		change_ifs ","
		for i in $MIDAS_PROD_LIST; do
			echo " ${ctr}. ${i}.         " > /dev/tty
			plist=`addto "$plist" "$ctr"`
			ctr=`expr $ctr + 1`
		done
		restore_ifs

		echo " A. Install ALL products." > /dev/tty
		echo " R. $RETURN_MSG." > /dev/tty
		plist="$plist,a,A,r,R"
		echo "                         " > /dev/tty
		pselect=`ask_multi 'Enter your list' "$plist"`

		case "$pselect" in
			[rR])	false; return
					;;
			[aA])	# Put all entries in pselect
					j=1
					pselect=
					while [ $j -lt $ctr ]; do
						pselect=`addto "$pselect" "$j"`
						j=`expr $j + 1`
					done
					;;
		esac

		#
		#  go back through $MIDAS_PROD_LIST and create MIDAS_PROD_SELECTED
		#  the list of selected products
		#

		change_ifs ","
		MIDAS_PROD_SELECTED=
		for j in $pselect; do
			ctr=1
			for i in $MIDAS_PROD_LIST; do
				if [ "$ctr" -eq "$j" ]; then
					case "$i" in
						$PROD_BIN)	[ -f $MIDASHOME/$MIDVERS/monit/prepa.exe ];;
						$PROD_SRC)	[ -f $MIDASHOME/$MIDVERS/monit/prepa.c ];;
						$PROD_GUI)	[ -f $MIDASHOME/$MIDVERS/gui/exec/help.exe ];;
						$PROD_DEMO)	[ -f $MIDASHOME/demo ];;
						$PROD_CALIB)	[ -f $MIDASHOME/calib ];;
					esac
					if [ $? -eq 0 ]; then
						echo "                                    " > /dev/tty
						echo "*** Directory $MIDASHOME seems to have" > /dev/tty
						echo "*** product $i already installed." > /dev/tty
						echo "                                    " > /dev/tty
						if ask_yn 'Do you want to overwrite this copy' n; then
							MIDAS_PROD_SELECTED=`addto "$MIDAS_PROD_SELECTED" "$i"`
						fi
					else
						MIDAS_PROD_SELECTED=`addto "$MIDAS_PROD_SELECTED" "$i"`
					fi
					break
				fi
				ctr=`expr $ctr + 1`
			done
		done
		restore_ifs
	fi

	isset_product
}

setup_product()
{
	# 
	# setup. Install links for shared libraries.
	# scripts and man pages.
	#
	if check_precond_setup; then
		clear > /dev/tty
		banner1
		if isset_su ; then
			if ask_yn 'OK to complete MIDAS installation'; then
				pick_mandir
				pick_bindir
        			case "$MIDAS_ARCH" in
                			$ARCH_ALPHA|$ARCH_SUNOS|$ARCH_SOLARIS)
				  		pick_libdir
						;;
					$ARCH_LINUX)
						echo $MIDASHOME/$MIDVERS/lib | cat /etc/ld.so.conf - | sort -u > /etc/ld_so_conf
						mv /etc/ld.so.conf /etc/ld.so.conf~
						mv /etc/ld_so_conf /etc/ld.so.conf
		  				/sbin/ldconfig
	  					MIDAS_LIBDIR_DONE="yes"
					  	;;
					$ARCH_HP700|$ARCH_SGI5)
						if [ "$MIDASHOME" != "/midas" ]; then
						  mv /midas /midas.org
						  rm -f midas.org 2>/dev/null
					  	  ln -s $MIDASHOME /midas
						fi
	  					MIDAS_LIBDIR_DONE="yes"
					  	;;
                        	esac
				if [ -n "$MIDAS_LIBDIR_DONE" -a -n "$MIDAS_BINDIR_DONE" ]; then
				  echo " " >/dev/tty
				  echo "ESO-MIDAS installation completed successfully." >/dev/tty
				  echo "Exit and type \"inmidas\" to start ESO-MIDAS" >/dev/tty
				  echo " " >/dev/tty
				  MIDAS_SETUP="OK"
				fi
				ask_return 
			fi
		else
			echo "Sorry. You need to be superuser to run this option" >/dev/tty
			ask_return
		fi	
	
	fi

	isset_setup_installed
}

install_product()
{
	#
	#  Install the chosen products.  
	#

	if check_precond_install; then
		clear > /dev/tty

		show_state
		if ask_yn 'OK to install this configuration'; then
			save_dir=`pwd`
			cd $MIDASHOME
			change_ifs ","

			MIDAS_PROD_INSTALLED=
			echo " " > /dev/tty
			for prod in $MIDAS_PROD_SELECTED; do
				case "$prod" in
					$PROD_BIN)		suffix=bin;;
					$PROD_SRC)		suffix=src;;
					$PROD_GUI)		suffix=gui;;
					$PROD_DEMO)		suffix=demo;;
					$PROD_CALIB)		suffix=calib;;
				esac
				if [ "$suffix" != "src" ]; then
					ifile=`ls $MIDAS_CDDIR|grep -i ${MIDAS_ARCH_PREFIX}.$suffix`
				else
					ifile=$MIDAS_SOURCES
				fi
				if [ -z "$ifile" ]; then
					error "Can't find product file ${MIDAS_ARCH_PREFIX}.$suffix for $prod"
					sleep 1
				else
					necho "Installing $prod ..." > /dev/tty
					COMMAND="zcat < $MIDAS_CDDIR/$ifile | tar xf -"
					if sh -c "$COMMAND" ; then
						MIDAS_PROD_INSTALLED=`addto "$MIDAS_PROD_INSTALLED" "$prod"`
					fi
					echo " " > /dev/tty
				fi
			done
			echo " " > /dev/tty

			restore_ifs
			cd $save_dir

			MIDAS_PROD_SELECTED=`difference "$MIDAS_PROD_SELECTED" "$MIDAS_PROD_INSTALLED"`
		fi
	fi

	isset_prod_installed
}

quit()
{
	ask_yn 'Are you sure you want to quit' y
}

infer_cddir()
{
	ifile=`ls |grep -i install.sh`
	if [ -n "$ifile" ]; then
		MIDAS_CDDIR=`pwd`
	else
		ifile=`ls /cdrom |grep -i install.sh`
		if [ -n "$ifile" ]; then
			MIDAS_CDDIR="/cdrom"
		fi
	fi
}


get_arch()
{
  case $1 in
    $REL_ALPHA)   MIDAS_ARCH=$ARCH_ALPHA   ; MIDAS_ARCH_PREFIX=alphaosf;;
    $REL_HP700)   MIDAS_ARCH=$ARCH_HP700   ; MIDAS_ARCH_PREFIX=hp700;;
    $REL_IBM)     MIDAS_ARCH=$ARCH_IBM     ; MIDAS_ARCH_PREFIX=rs6000;;
    $REL_SGI5)    MIDAS_ARCH=$ARCH_SGI5    ; MIDAS_ARCH_PREFIX=sgirix5;;
    $REL_SUNOS)   MIDAS_ARCH=$ARCH_SUNOS   ; MIDAS_ARCH_PREFIX=sparcsun;;
    $REL_SOLARIS4) MIDAS_ARCH=$ARCH_SOLARIS ; MIDAS_ARCH_PREFIX=sparcsol;;
    $REL_SOLARIS5) MIDAS_ARCH=$ARCH_SOLARIS ; MIDAS_ARCH_PREFIX=sparcsol;;
    $REL_LINUX)   MIDAS_ARCH=$ARCH_LINUX   ; MIDAS_ARCH_PREFIX=pclinux;;
  esac
}

infer_arch()
{
  MIDAS_PROD_SELECTED=""
  MIDAS_PROD_INSTALLED=""

  UNAME=`(uname) | sed 's/\//-/g' 2>/dev/null`
  URELS=`(uname -r) 2>/dev/null`

  get_arch "${UNAME}_$URELS"
  if [ -z "$MIDAS_ARCH" ] ;then
    get_arch "$UNAME"
  fi
}


select_action()
{
	#  The main routine.  It just keeps prompting the user to perform
	#  one of the listed actions.  The loop is broken when the user
	#  affirms the quit.

	MIDAS_STATE=1
	while true; do
		clear > /dev/tty

		set_state
		show_state

		pre1=" "
		pre2=" "
		pre3=" "
		pre4=" "
		pre5=" "
		pre6=" "
		pre7=" "
		preQ=" "

		echo "                                                                " > /dev/tty
		echo "  Choose one of the following actions:                       " > /dev/tty

		case "$MIDAS_STATE" in
			1)	pre1=">";;
			2)	pre2=">";;
			3)	pre3=">";;
			4)	pre4=">";;
			5)	pre5=">";;
			6)	pre6=">";;
			7)	pre7=">";;
			Q)	preQ=">";;
		esac

		echo "                                                                " > /dev/tty
		echo "${pre1}1. Enter the CD mount point.                             " > /dev/tty
		echo "${pre2}2. Select architecture.                                  " > /dev/tty
		echo "${pre3}3. Enter the installation directory (MIDASHOME).         " > /dev/tty
		echo "${pre4}4. Select ESO-MIDAS product(s) to install.               " > /dev/tty
		echo "${pre5}5. Install ESO-MIDAS product(s).                         " > /dev/tty
		echo "${pre6}6. Complete ESO-MIDAS installation in your system.       " > /dev/tty
		echo "${preQ}Q. Quit.                                                 " > /dev/tty
		echo "                                                                " > /dev/tty
		select=`ask_list 'Enter your selection' "1,2,3,4,5,6,q,Q" $MIDAS_STATE`
		case "$select" in
			   1) if pick_cddir;       then MIDAS_STATE=`expr $select + 1`; fi;;
			   2) if pick_arch;        then MIDAS_STATE=`expr $select + 1`; fi;;
			   3) if pick_midashome;   then MIDAS_STATE=`expr $select + 1`; fi;;
			   4) if pick_product;     then MIDAS_STATE=`expr $select + 1`; fi;;
			   5) if install_product;  then MIDAS_STATE=`expr $select + 1`; fi;;
			   6) if setup_product;    then MIDAS_STATE="$STATE_QUIT"; fi;;
			[qQ]) if quit; then break; fi;;
			   *) fatal_error "Improper selection $select in select_action";;
		esac
	done
}

##############################################################################
#
#  Main Processing here
#
##############################################################################

banner
ask_return 

infer_cddir
infer_arch
select_action

post_install

exit 0
