#!/bin/bash -f
#------------------------------------------------------------------------------
# Script to retry Son-of-Spectro jobs.
#
# Example: Retry reductions for exposure #12551:
#   sos_redo expnum=12551
# Example: Retry reductions for plate 328:
#   sos_redo plate=328
# Example: Retry reductions for plate 328 on the remote machine "sos":
#   sos_redo sos plate=328
# Example: Retry reductions for plate 328 on MJD 51234:
#   sos_redo plate=328 mjd=51234
# (This last example will only work if the SOS reductions have not been
# removed from disk, which is usually done by a cron job each morning.)
#
# This script will not run if it looks like it is already running.
#
# Set the default location for SPECLOG_DIR=/data/spectro/astrolog???
#
# In detail, if there is an argument on the command-line not of the
# form "a=b", then we assume that is the name of a remote machine and
# execute the rest of the command on that remote machine.  All other
# arguments are passed to the IDL procedure REMOVE2REDO; the last example
# above would result in the following begin executed:
#   echo "remove2redo,plate=328" | idl
#------------------------------------------------------------------------------

bashstring=sos_redo
idlstring=remove2redo
remotehost=""

for thisarg in "$@" ; do
  if [ `echo "$thisarg" | grep "="` ] ; then
    bashstring="$bashstring $thisarg"
    idlstring="$idlstring,$thisarg"
  else
    # This argument does not have an equal sign, so assume it is a host name
    remotehost=$thisarg
  fi
done

if [ -n "$remotehost" ] ; then
  echo Executing this command remotely on host=$remotehost
  echo ssh $remotehost $bashstring
  ssh $remotehost $bashstring
  exit
fi

#------------------------------------------------------------------------------
# Don't allow this to be run from the machine "sdsshost"!

echo

if [ `uname -n` = "sdsshost" ] ; then
  echo "You are not allowed to launch Son-of-Spectro from sdsshost!"
  exit
fi

#------------------------------------------------------------------------------
# Don't run if it looks like it already is running.
# (If it's already running, then I get 2 processes because the back-quoted
# command launches another shell.)

nrunning=`\ps -elf | grep sos_redo | grep -v -e grep | wc -l`
if [ $nrunning -gt 2 ] ; then
  echo It appears as though sos_redo is already running.
  exit
fi

#------------------------------------------------------------------------------
# Attempt to run the idl procedure remove2redo

echo Executing: echo \"$idlstring\" "|" idl
echo "$idlstring" | idl

#------------------------------------------------------------------------------
