#! /bin/sh
# .COPYRIGHT: Copyright (c) 1988-2007 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.
#		  -drs:	     reuse keyfile from drs commands
#		  -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.0	this is the modified inmidas script for Sun Solaris 8
#		where we don't have the shell command "lockfile"
# 
# 070716	last modif
# 
#**************************************************************************

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

MIDASHOME0=/home/esomidas
MIDVERS0=test

#
# END of Configure Here
#**************************************************************************

#
DAZUNIT=''
MIDASDRS=''; export MIDASDRS 
#
# Check command "echo"
#
echo=echo
SV_NONL=
if [ "`echo -n`" = "-n" ] ; then
  SV_NONL="\c"
else
  echo="echo -n"
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

#**************************************************************************

#
# 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\"] [-drs] [-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 (in [01, ..., 99])."
echo "     With -p option and no unit, the user 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 "     terminals other than X (no graphics). If no unit is provided the "
echo "     system 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 "-drs"
echo "     Starts a MIDAS session which reuses an existing FORGRdrs.KEY in the "
echo "     current directory, by default this keyfile is recreated each time."
echo "-help"
echo "     Display this help page."
       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 ;;
  -drs) MIDASDRS=yes; export MIDASDRS; 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 or MIDVERS variable not defined then set to default
#
if [ -z "$MIDASHOME" ]; then
   MIDASHOME="$MIDASHOME0"; export MIDASHOME
fi
if [ -z "$MIDVERS" ]; then
   MIDVERS="$MIDVERS0"; export MIDVERS
fi

#
# Check access to Midas directory
#
if [ ! -d $MIDASHOME/$MIDVERS ]; then
  echo "$MIDASHOME/${MIDVERS}: no such directory."
  echo "Call your MIDAS operator. EXIT."
  exit 1
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 - no such file."
  echo "Call your MIDAS operator. EXIT."
  exit 1
fi

#
# Set default DAZUNIT to first unit free (~/midwork/RUNNING<unit>)
# 
if [ -z "$DAZUNIT" -a \( -z "$MIDOPTION" -o "$MIDOPTION" = "NOPARALLEL" -o "$SELECT_UNIT" = "AUTO" \) ]
then

#
#  we don't have this command in Solaris 8 
#
###  lockfile -1 -r 10 $MID_WORK/running.lock 
# 
# 
 if [ $? != 0 ] ; then
    DAZUNIT=99

 else
  DAZUNIT=`(ls $MID_WORK/RUNNING?? 2>/dev/null) | awk ' \
  { \
  tmp = index($1,"RUNNING"); \
  unit[substr($1,tmp+7,2)+0] = 1 \
  } \

  END { \
    i = 1; \
    while (i < 100) { \
      if (!unit[i]) { \
        if (i < 10) 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 \
    }' `
  fi


  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

#
# logical assignements to devices. 
#
if [ -f $MID_WORK/devices.sh ] ; then
  . $MID_WORK/devices.sh
else
  . $MIDASHOME/$MIDVERS/monit/devices.sh
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

  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 other
  *) 		
    DAZUNIT=`echo $DAZUNIT | tr "[a-z]" "[A-Z]" `     # convert to upper case
    case $DAZUNIT in
    #                        no graphics capabilities
    [XYZ]?)
      WORK_STATION=DAZ$DAZUNIT
      I_TYPE="NULL "
      ;;
    *) 		
      echo "invalid Midas unit: $DAZUNIT"
      DAZUNIT=''
      continue
      ;;
    esac
    ;; 
  #
  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 \
        getXdepth* midas_xw* MIDAS*.PID RUNNING* xhelp*

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

# 
# no lockfile for Solaris 8
# 
### rm -f $MID_WORK/running.lock
# 

#
# 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 used 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
