#! /bin/bash
##
## "@(#) $Id: ferosMkferoNNNNLink,v 1.5 2005/08/08 17:44:54 jpritcha Exp $"

if [ -x /bin/hostname ]; then
  [ `/bin/hostname` == "w2p2off" ] && ISw2p2off="T"
fi

usage() {
  printf "\
Usage: feroMkferoNNNNLink [-h|qrvw] <file>  [-d <DRS-directory>] [--qdir <Queue-directory>]
                          [--dbdir <DB-directory>] [--maxWait <sec>]
"
  exit ${exstat:-0}
}

# The Maximum time [sec] to wait for a file to exist before exiting with error status
maxWait=300

while [ -n "$1" ]; do
  case $1 in
  -h)        usage;;
  --help)    usage;;
  -d)        ddir="${2}"; shift; shift;;
  --dbdir)   dbdir="${2}"; shift; shift;;
  --dml)     dmlink=1; shift;;
  --focOff)  focOff="p4=$2"; shift; shift;;
  -i)        indexFile="${2}"; shift; shift;;
  -q)        [ ! -z "${ISw2p2off}" ] && dque=1; shift;;
  --qdir)    [ ! -z "${ISw2p2off}" ] && Qdir="${2}"; shift; shift;;
  --procIm)  [ ! -z "${ISw2p2off}" ] && procIm=1; shift;;
  -r)        [ ! -z "${ISw2p2off}" ] && AutoRed=1; shift;;
  -v)        vbose=1; shift;;
  -w)        WaitForFileToExist=1; shift;;
  --maxWait) maxWait="${2}"; shift; shift;;
  --usepwd)  usePwd="`pwd`/"; shift;;
  *)         file="$1"; shift;;
  esac
done

if [ -z ${file} ]; then
  exstat=1
  usage
fi

# Set defaults...
nnnn=1
[ -z "${ddir}" ] && ddir="/data/reduced/FEROS/DRS"
[ -z "${dbdir}" ] && dbdir=$ddir
[ -z "${Qdir}" ] && Qdir="/data/reduced/FEROS/DRS-Queue"
ghfile="${usePwd}${file}"
[ -z "${indexFile}" ] && indexFile=${dbdir}/.feroNNNN

# Work out the next sequential number...
## Has the file already been linked...
arcFile="`gethead ${usePwd}$file ARCFILE`"
origFile="`gethead ${usePwd}$file ORIGFILE`"
if [ -e ${ddir}/feroNNNN.log ]; then
  grep $arcFile ${ddir}/feroNNNN.log > /dev/null 2>&1
  if [ $? -eq 0 ]; then
    lnFile=`grep $arcFile ${ddir}/feroNNNN.log | cut -f5 -d= | cut -b2-`
    NNNN="`echo $lnFile | cut -b5-8`"
    if [ ! -e "${ddir}/${lnFile}" ]; then
      ln -s ${usePwd}${file} ${ddir}/fero${NNNN}.mt
    fi
    if [ ! -z $vbose ]; then
      /bin/echo "${ddir}/fero${NNNN}.mt --> ${usePwd}${file}"
      /bin/echo "$origFile == $arcFile == fero${NNNN}.mt"
    fi
    dmlink=1
  fi
fi

if [ -n $WaitForFileToExist ]; then
  wloop=0
  [ ! -e ${usePwd}${file} ] && /bin/echo "Waiting till ${usePwd}${file} exists..."
  while [ ! -e ${usePwd}${file} ] && [ $wloop -lt $maxWait ]; do
    (( wloop = wloop+1 ))
    sleep 1
  done
  if [ $wloop -ge $maxWait ]; then
    /bin/echo "Error!!! File ${usePwd}${file} does NOT exist after $maxWait secs"
    exit 1
  fi
fi
# Make the soft link....
if [ -z $dmlink ]; then
  [ -e ${indexFile} ] && nnnn=`cat ${indexFile}`
  NNNN="`printf "%04d" $nnnn`"
  while [ -e ${ddir}/fero${NNNN}.mt ] || [ -h ${ddir}/fero${NNNN}.mt ]; do
    (( nnnn = nnnn + 1 ))
    NNNN="`printf "%04d" $nnnn`"
  done
  touch ${ddir}/feroMkLink.log
  /bin/echo "ln -s ${usePwd}${file} ${ddir}/fero${NNNN}.mt" >> ${ddir}/feroMkLink.log
  ln -s ${usePwd}${file} ${ddir}/fero${NNNN}.mt
  touch ${ddir}/feroNNNN.log
  /bin/echo "$origFile == $arcFile == fero${NNNN}.mt" >> ${ddir}/feroNNNN.log
  if [ ! -z $vbose ]; then
    /bin/echo "${ddir}/fero${NNNN}.mt --> ${usePwd}${file}"
    /bin/echo "$origFile == $arcFile == fero${NNNN}.mt"
  fi
  (( nnnn = nnnn + 1 ))
  /bin/echo $nnnn > ${indexFile}
  ghfile="${ddir}/fero${NNNN}.mt"
fi

## Archive...
if [ ! -z $procIm ]; then
  arcName="`gethead ${ghfile} ARCFILE`"
  mjd="`gethead $file MJD-OBS`"
  date="`ferosMJD2DSofN.pl $mjd`"
  ferosProcImage astro@w2p2dhs:/data/raw/${date}/${arcName} --pidir ${FEROS_DRS}/procImage/Archive
  [ ! -z $vbose ] && /bin/echo "Queueing astro@w2p2dhs:/data/raw/${date}/${arcName} for Archival copy"
  ferosProcImage astro@w2p2dhs:/data/raw/${date}/${arcName} --pidir ${FEROS_DRS}/procImage/VA
  [ ! -z $vbose ] && /bin/echo "Queueing astro@w2p2dhs:/data/raw/${date}/${arcName} for VAs copy"
fi

# Pass on to DRS...\
if [ -z $AutoRed ]; then
  # Queue for reduction if requested...
  if [ ! -z $dque ]; then
    [ ! -z $vbose ] && /bin/echo "Queueing in $Qdir [ferosCommandToMidas 9~ @@ loadccd fero $NNNN $focOff]"
    daemonq $Qdir -a "ferosCommandToMidas 9~ @@ loadccd fero $NNNN $focOff"
  fi
else
  [ ! -z $vbose ] && /bin/echo "Submitting to DRS [ferosCommandToMidas 9~ @@ loadccd fero $NNNN $focOff]..."
  ferosCommandToMidas 9~ @@\ loadccd\ fero\ $NNNN\ $focOff
  exstat=$?
  if [ $exstat -ne 0 ]; then
    # Queue for reduction if requested...
    if [ ! -z "${dque}" ]; then
      [ ! -z $vbose ] && /bin/echo "Failed to submit to DRS, adding to queue in $Qdir"
      daemonq $Qdir -a "ferosCommandToMidas 9~ @@ loadccd fero $NNNN $focOff"
      exstat=$?
    fi
  fi
fi

exit ${exstat:-0}
