#! /bin/sh
# @(#)inmidas.sh	16.1.1.2 (ESO-IPG) 09/05/01 14:13:11
# .COPYRIGHT: Copyright (c) 1988 European Southern Observatory,
#
# .TYPE         command
# .NAME         inmidas
# .LANGUAGE     Bourne-shell script
# .ENVIRONMENT  Unix Systems. Executable under any SHELL.
# .USAGE        inmidas [ unit ] [-h midashome] [-r midvers] [-d display] 
#		[-m mid_work] [-p/-np] [-noh ] [-j midas-comman-line]
#		  unit:      MIDAS unit (00, 01, ..., 99, xa, ..., zz)
#			     (default: 00 if NOPARALLE mode)
#		  display:   X server for display and graphical windows.
#		  midashome: Home directory for MIDAS. (default: MIDASHOME0)
#		  midvers:   Version of MIDAS. (default: MIDVERS0)
#		  mid_work:  MIDAS startup directory (default: $HOME/mid_work)
#		  -p/-nop:   Set MIDOPTIONS to PARALLEL/NOPARALLE 
#			     (default: NOPARALLEL)
#		  -noh:	     No welcome header.
#		  -j:	     Execute next argument as a MIDAS command.
#
# .COMMENTS     Script to start MIDAS. It uses the following environment:
#		MIDASHOME, MIDVERS and MIDOPTION.
#		variables if they exist, otherwise takes defaults.
#		It checks arguments if any and exec to 
#		$MIDASHOME/$MIDVERS/monit/prepa.exe
#
# .REMARKS      MIDASHOME0 & MIDVERS0 are set to defaults values by option
#               "8- MIDAS setup" in the MIDAS "config" script.
#
# .VERSION 1.1	910221:	CG. Implementation
# .VERSION 2.1	930706:	CG. Simplified and passing arguments.
# .VERSION 2.2	010831:	KB. remove all Midas related files in $MID_WORK
# 
#**************************************************************************

#**************************************************************************
# Configure Here: 
# ---------------
# Modify the default values of MIDASHOME0 and MIDVERS0 
# accordingly to your site. 
#
# Environment variables MIDASHOME and MIDVERS overwrite these defaults.
#
# Done automaticaly by option "8- setup MIDAS" in the "config" script.
#
MIDASHOME0=/midas
MIDVERS0=95NOV
#
# END of Configure Here
#**************************************************************************

#
# unset DAZUNIT to be sure they are not taken from
# the environment
# CG. I do not like MID_WORK and MIDOPTIONS either, but I keep them for
#     backward compatibility.
#
# unset command does not exist on Ultrix. CG. 21.07.93
#unset DAZUNIT 
DAZUNIT=''

#
# Check for options:
#
while [ -n "$1" ]
do
  case $1 in
  -help) 
echo "Usage: inmidas [unit] [-h midashome] [-r midvers] [-d display] [-p/-P/-nop]"
echo "       [-m mid_work] [-noh] [-j \"midas-command-line\"] [-help]"
echo "Options:"
echo "-h midashome"
echo "     Home directory for MIDAS. Sets variable MIDASHOME to midashome"
echo "-r midvers"
echo "     Release of MIDAS. Sets variable MIDVERS to midvers and it must exist as "
echo "     a subdirectory under MIDASHOME."
echo "-d display"
echo "     This option specifies the X server to contact."
echo "-p/-P/-nop"
echo "     -p and -P options set variable MIDOPTION to PARALLEL. -nop option"
echo "     sets MIDOPTION to NOPARALLEL."
echo "     With -nop (NOPARALLEL) all working files from previous MIDAS sessions"
echo "     located in the directory MID_WORK are deleted. Only one MIDAS session can"
echo "     run at a time. With -p and -P (PARALLEL) no working files are removed" 
echo "     from MID_WORK and several sessions can run simultaneously."
echo "     With -P and -nop options and if not unit is given the system will select"
echo "     automatically one free unit for you. With -p option and no unit, the user"
echo "     will be requested to enter one."
echo "unit"
echo "     Unit to be associated to the MIDAS session. Valid values for this option"
echo "     are in the range (00 to 99) for X environments, or (xa to zz) for ASCII"
echo "     or graphical terminals other than X. If no unit is provided the system"
echo "     will select one for you except with -p option." 
echo "-m mid_work"
echo "     This option sets the MID_WORK variable that specifies the MIDAS working"
echo "     directory. By default MID_WORK is set to ~/midwork and it will be created"
echo "     if it does not exist."
echo "-noh"
echo "     Starts a MIDAS session without clearing the terminal and without any"
echo "     welcome message. This option is meant for background purposes."
echo "-j \"midas_command_line\""
echo "     Execute \"midas_command_line\" as the first command typed in the MIDAS"
echo "     monitor. This option sets also -noh option."
echo "-help"
echo "     Display this help page and exits quietly."
       exit 0 ;;
  -h)   MIDASHOME=$2; export MIDASHOME; shift; shift ;;
  -r)   MIDVERS=$2; export MIDVERS; shift; shift ;;
  -d)   DISPLAY=$2; export DISPLAY; shift; shift ;;
  -m)   MID_WORK=$2; export MID_WORK; shift; shift ;;
  -P)   SELECT_UNIT=AUTO; MIDOPTION=PARALLEL; export SELECT_UNIT MIDOPTION; shift ;;
  -p)   MIDOPTION=PARALLEL; export MIDOPTION; shift ;;
  -nop) MIDOPTION=NOPARALLEL; export MIDOPTION; shift ;;
  -noh) MIDASHD=noheader; export MIDASHD; shift ;;
  -j)   MIDASJOB=$2; export MIDASJOB; shift; shift ;;

  -*)   echo "Usage: inmidas [unit] [-h midashome] [-r midvers] [-d display] [-p/-P/-nop]"
        echo "       [-m mid_work] [-noh] [-j \"midas-command-line\"] [-help]" >&2
       exit 1 ;;
  *)   DAZUNIT=$1; export DAZUNIT; shift ;;
  esac
done

#
# If MIDASHOME variable not defined then set to default.
#
if [ -z "$MIDASHOME" ]; then
  if [ -z "$MIDASHOME0" ]; then
    echo "inmidas - ERROR: Environment variable MIDASHOME not defined" >&1
    echo "          and no default MIDASHOME0 found in this script. EXIT." >&1
    exit 1
  else
    MIDASHOME="$MIDASHOME0"; export MIDASHOME
  fi
fi

#
# If MIDVERS variable not defined then set to default.
#
if [ -z "$MIDVERS" ]; then
  if [ -z "$MIDVERS0" ]; then
    echo "inmidas - ERROR: Environment variable MIDVERS not defined" >&2
    echo "          and no default MIDVERS0 found in this script. EXIT." >&2
    exit 1
  else
    MIDVERS="$MIDVERS0"; export MIDVERS
  fi
fi

#
# Check access to directories and files
#
if [ ! -d $MIDASHOME ]; then
  echo "${MIDASHOME}: not such directory."
  echo "Call your MIDAS operator. EXIT."
  exit 1
fi
if [ ! -d $MIDASHOME/$MIDVERS ]; then
  echo "$MIDASHOME/${MIDVERS}: not such directory."
  echo "Call your MIDAS operator. EXIT."
  exit 1
fi

#
# Check command "echo"
#
echo=echo
SV_NONL=
if [ "`echo -n`" = "-n" ] ; then
  SV_NONL="\c"
else
  echo="echo -n"
fi

#
# if necessary create MIDAS work directory
#
if [ -z "$MID_WORK" ]; then
  MID_WORK=$HOME/midwork/ ; export MID_WORK
fi

#
# if last char. of MID_WORK != '/'  append a '/'
#
if [ `expr $MID_WORK : '.*\(.\)'` != '/' ]; then
  MID_WORK=$MID_WORK/ ; export MID_WORK
fi

if [ ! -d $MID_WORK ]; then
  mkdir `expr $MID_WORK : '\(.*\).'`         #use MID_WORK except last char.
  if [ $? != 0 ]; then
    echo Could not create directory `expr $MID_WORK : '\(.*\).'`
    exit 1
 fi
fi

#
# get all the variables (logical names)
#
if [ -f $MIDASHOME/$MIDVERS/monit/midlogs.sh ]; then
  . $MIDASHOME/$MIDVERS/monit/midlogs.sh
else
  echo "$MIDASHOME/$MIDVERS/monit/midlogs.sh not such file."
  echo "Call your MIDAS operator. EXIT."
  exit 1
fi

#
# Set default DAZUNIT to the first unit free (~/midwork/RUNNING<unit>)
# 
if [ -z "$DAZUNIT" -a \( -z "$MIDOPTION" -o "$MIDOPTION" = "NOPARALLEL" -o "$SELECT_UNIT" = "AUTO" \) ]
then
 DAZUNIT=`(ls $MID_WORK/RUNNING?? 2>/dev/null) | awk '{ \
  tmp = index($1,"RUNNING"); \
  unit[substr($1,tmp+7,2)+0] = 1 \
  } \
  END { \
    i=0; \
    while (i < 100) { \
      if (!unit[i]) {
        if (unit[i] < 100) printf "0%d\n",i; \
        else printf "%d\n",i ;
        break \
        } \
      else i++ \
      } \
    if (i == 100) { \
      printf "inmidas - Error: Too many MIDAS sessions already running.\n"; \
      exit 1 \
      } \
    exit 0 \
    }'`
  if [ $? -ne 0 ]; then
    echo $DAZUNIT >&2
    exit 1
  fi
fi

#
# If AUTOPARALLEL, DAZUNIT is now selected, and MIDOPTION is set to PARALLEL
#
if [ "$MIDOPTION" = "AUTOPARALLEL" ]; then
  MIDOPTION = PARALLEL
fi
#
# Strip "/dev/", strip "pty/" (HP), "pts/" (IBM), and "tty" (all)
#
if ( tty -s )
then
  tt=`tty | sed -e 's/^.*dev\///' -e 's/pty\///' -e 's/pts\///' -e 's/tty//'`
else
  tt=none
fi

#
# logical assignements to devices. 
#
if [ -f $MID_WORK/devices.sh ] ; then
  . $MID_WORK/devices.sh
else
  . $MIDASHOME/$MIDVERS/monit/devices.sh
fi

#
# set TERMWIN to "yes" in any other previous release to 94NOV 
#
#if [ -z "$TERMWIN" -a "$MIDVERS" != "94NOV" ]; then
#  TERMWIN=yes; export TERMWIN
#fi

#
# test, if DAZUNIT defined
# 
while :
do
  if [ -z "$DAZUNIT" ]; then
    $echo "Enter Midas unit (00, 01, ..., 99, xa, ..., zz) " $SV_NONL
    read DAZUNIT
    if [ -z "$DAZUNIT" ]; then
      DAZUNIT=''
      continue
    fi
  fi

  DAZUNIT=`echo $DAZUNIT | tr "[a-z]" "[A-Z]" `     # convert to upper case
  case $DAZUNIT in
  #                          here for X Workstations
  [0123456789]?)
    WORK_STATION=DAZ$DAZUNIT
    I_TYPE="SXW  " 
    ;;
  AX)
    WORK_STATION=DAZAX
    I_TYPE="SXW  " 
    ;;
  #                          here for any ASCII/graphics terminal
  [PQRSTUXYZ]?)
    WORK_STATION=DAZ$DAZUNIT
    I_TYPE="NULL "
    if [ -z "$AGL3DEV" ]; then
      AGL3DEV=tkg.vt640
    fi
    graph_term=tt ; export graph_term
    ;;
  #
  # here you should insert your specific image display device ...!!!
  #
  *) 		
    echo "Invalid Midas Unit: $DAZUNIT" 
    DAZUNIT=''
    continue
    ;;
  esac
  break
done
#
export DAZUNIT WORK_STATION I_TYPE AGL3DEV 

#
# Check if there is a running session already for DAZUNIT.
#
if [ -f "$MID_WORK/RUNNING$DAZUNIT" ]; then
  echo "Unit $DAZUNIT is locked by another MIDAS session."
  echo "To unlock just continue."
  $echo "Do you want to continue [yn]? (n): " $SV_NONL
  read answ
  if [ -z "$answ" ]; then
    answ=n
  fi
  if [ "$answ" != "y" -a "$answ" != "Y" ]; then
    exit 1
  fi
  rm -f $MID_WORK/RUNNING$DAZUNIT
fi

#
# Check PARALLEL option in MIDOPTION.
#
if [ -z "$MIDOPTION" ]; then 
  MIDOPTION=NOPARALLEL; export MIDOPTION
fi
#

if [ "$MIDOPTION" != "PARALLEL" -a "$MIDOPTION" != "parallel" ] ; then
  # echo Deleting old MIDAS files ... 
  # Ensure at least one file is deleted.
  HERE=`pwd`
  cd $MID_WORK
  if (ls * 2>/dev/null | grep -s RUNNING)
  then
    echo "WARNING: Other MIDAS sessions might be running."
    echo "Exit and use option <-p> for PARALLEL mode."
    echo "If you continue all previous MIDAS sessions will be removed."
    $echo "Do you want to continue [yn]? (n): " $SV_NONL
    read answ
    if [ -z "$answ" ]; then
      answ=n
    fi
    if [ "$answ" != "y" -a "$answ" != "Y" ]; then
      exit 1
    fi
  fi
  rm -f middum* midtemp* midjob*.prg midlis*.prg midtab*.prg \
        IDISERV* idiserv* idisave*.dat .inmidas* CODE*.SAV sxw*.dat \
        midas_xw* MIDAS*.PID RUNNING* xhelp*

  cd $HERE
  # delete all &a,&b, ... files
  rm -f middum* midtemp* >/dev/null 2>&1

else
  rm -f midas_xw$DAZUNIT xhelp$DAZUNIT Midas_osx$DAZUNIT RUNNING$DAZUNIT \
        MIDAS${DAZUNIT}.PID
fi

#
# Catch any possible interrupt and remove the lock file
#
trap "rm -f $MID_WORK/RUNNING$DAZUNIT; exit 1" 1 2 3 15
touch $MID_WORK/RUNNING$DAZUNIT

#
# Prepare $MID_WORK/.inmidas for next gomidas command
#
rm -f $MID_WORK/.inmidas $MID_WORK/.inmidas.$tt >/dev/null 2>&1
echo "# Date: " `date` 				  > $MID_WORK/.inmidas
echo "MIDASHOME=$MIDASHOME; export MIDASHOME"    >> $MID_WORK/.inmidas
echo "MIDVERS=$MIDVERS; export MIDVERS"    	 >> $MID_WORK/.inmidas
echo "MIDOPTION=$MIDOPTION; export MIDOPTION"    >> $MID_WORK/.inmidas
echo "DAZUNIT=$DAZUNIT; export DAZUNIT" 	 >> $MID_WORK/.inmidas
echo "WORK_STATION=$WORK_STATION; export WORK_STATION" >> $MID_WORK/.inmidas
echo "I_TYPE=$I_TYPE; export I_TYPE" 		 >> $MID_WORK/.inmidas
if [ -n "$AGL3DEV" ]; then
  echo "AGL3DEV=$AGL3DEV; export AGL3DEV" 	 >> $MID_WORK/.inmidas
fi
if [ -n "$graph_term" ]; then
  echo "graph_term=$graph_term; export graph_term"  >> $MID_WORK/.inmidas
fi

#
# Copy .inmidas to inmidas.<tt> that will be use by gomidas afterwards.
#
cp $MID_WORK/.inmidas $MID_WORK/.inmidas.$tt

#
# Set PATH for shared libraries
#
os=`uname`
case "$os" in
    "SunOS"|"Linux")
	if [ -z "$LD_LIBRARY_PATH" ] ; then
	  LD_LIBRARY_PATH=$MIDASHOME/$MIDVERS/lib
	else
	  LD_LIBRARY_PATH=$MIDASHOME/$MIDVERS/lib:$LD_LIBRARY_PATH
	fi
	export LD_LIBRARY_PATH
	;;
    "HP-UX")
	if [ -z "$SHLIB_PATH" ] ; then
	  SHLIB_PATH=$MIDASHOME/$MIDVERS/lib
	else
	  SHLIB_PATH=$MIDASHOME/$MIDVERS/lib:$SHLIB_PATH
	fi
	export SHLIB_PATH
	;;
     *)
	;;
esac

#
# run MIDASGO 
#
$MID_MONIT/midasgo.exe	
if  [ $? = 1 ] ; then
  echo "...Midas session aborted..."
  rm -f $MID_WORK/RUNNING$DAZUNIT
  exit 1
fi

#
# Ignore CTRL-C before runnning prepa.exe
#
trap "" 2

# run PREPA
#
$MID_MONIT/prepa.exe
if  [ $? = 1 ] ; then
  echo "...Midas session aborted..."
  rm -f $MID_WORK/RUNNING$DAZUNIT
  exit 1
fi

#
# remove lock file
#
rm -f $MID_WORK/RUNNING$DAZUNIT

exit 0
