#! /bin/bash
# "@(#) $Id: ferosPackFFsolArchiveTGZ,v 1.6 2004/12/04 00:55:50 jpritcha Exp $"

usage() {
  echo "Usage: ferosPackFFsolArchiveTGZ [-hv] [-t tar.gz] <LLLL> <NNNN> <MMMM>"
  echo " "
  echo "<LLLL> <NNNN> <MMMM>"
  echo "   File numbers as in FFsolArchive<LLLL>_<NNNN>_<MMMM>.tar.gz"
  echo "-v"
  echo "   Verbose"

  exit $exstat
}

while [ -n "$1" ]
do
  case $1 in
    -h)   usage;;
    -t)   targz=$2; shift; shift;;
    -v)   vbose="v"; shift;;
     *)   LLLL=$1; NNNN=$2; MMMM=$3; shift; shift; shift;;
  esac
done

if [ -z "${NNNN}" ] || [ -z "${MMMM}" ] || [ -z "${LLLL}" ]; then
  echo "Error!!! Must at least supply file numbers LLLL, NNNN and MMMM as in FFsolArchive<LLLL>_<NNNN>_<MMMM>.tar.gz"
  exit 1
fi

if [ -e ${INTROOT}/bin/ferosSetEnvVars ]; then
  . ${INTROOT}/bin/ferosSetEnvVars
fi

[ -z "${targz}" ] && targz=FFsolArchive${LLLL}_${NNNN}_${MMMM}.tar.gz
if [ -e ${targz} ]; then

# Get Variables from header...
  if [ ! -z "`gethead fero${NNNN}.mt PROGID`" ]; then
## Probably a BIAS image...
    ProgId="`gethead fero${NNNN}.mt PROGID`"
    YYYYMMDD="`gethead fero${NNNN}.mt DATE-OBS`"
    TMSTART="`gethead fero${NNNN}.mt TM_START`"
    ArchFile="`gethead fero${NNNN}.mt ARCFILE`"
    DSoN="`dateStartofNight.pl $YYYYMMDD $TMSTART`"
    ArchTar="${ArchFile/fits/tar}"
  elif [ ! -z "`gethead fero${NNNN}.mt 'HIERARCH ESO OBS PROG ID'`" ]; then
## Probably a FIERA image...
    ProgId="`gethead fero${NNNN}.mt 'HIERARCH ESO OBS PROG ID'`"
    ArchFile="`gethead fero${NNNN}.mt ARCFILE`"
#    dateObs="`gethead fero${NNNN}.mt DATE-OBS`"
#    ymd="`echo $dateObs | cut -b1-10`"
#    hh="`echo $dateObs | cut -b12-13`" ; hh=`printf %d $hh`
#    mm="`echo $dateObs | cut -b15-16`" ; mm=`printf %d $mm`
#    ss="`echo $dateObs | cut -b18-19`" ; ss=`printf %d $ss`
#    (( tmstart = hh * 3600 + mm * 60 + ss ))
#    DSoN="`dateStartofNight.pl $ymd $tmstart`"
    mjd="`gethead fero${NNNN}.mt MJD-OBS`"
    DSoN="`ferosMJD2DSofN.pl $mjd`"
    ArchTar="${ArchFile/fits/tar}"
  fi

# Make Directories if necessary
  if [ ! -d "${ProgId}" ]; then
    mkdir "${ProgId}"
  fi
  if [ ! -d "${ProgId}/${DSoN}" ]; then
    mkdir "${ProgId}/${DSoN}"
  fi

# Make the tar file with the data...
  if [ "${vbose:-0}" == "v" ]; then
    echo "create symbolic link ${ProgId}/${DSoN}/${targz} to ../../${targz}"
  fi
  ln -fs ../../${targz} ${ProgId}/${DSoN}/${targz}
# Make the tar file that will be used to copy across to VADRL
  tar --force-local -hc${vbose}f packFFsolArchive${targz}.tar ${ProgId}/${DSoN}/${targz}
  gzip -9${vbose} --force packFFsolArchive${targz}.tar

# Process tar file onto VADRL
  if [ "${FEROSProcImage:-N}" == "Y" ]; then
    ferosProcImage --pidir ${FEROS_DRS}/procImage/VA `pwd`/pack${targz}
  fi

fi

exit
