#!/bin/bash

# File containing the access credentials for the database
CREDENTIALS=credentials-read-only.cnf

# Specify the telescope for which to run the script. Replace '1' 
# by $1 if the telesocpe number is supplied as an option to the script
TELESCOPE=1

# The data is expected to be found in /data/raw and data/callisto
DATA="/data"
CALLISTO=callisto
# The .success file in /data/star will be resetted
STAR=star
# Directory to Mars environment (usually Mars/build)
MARS=~/Mars/build
# Relative path to macros
MACROS=../hawc

# Get all runs that can (and should) be calibrated
# Pipe the output to mysql and read the
# mysql output line-by-libe
echo \
"\
SELECT 
    NIGHT, RUNID, DrsNight, DrsRunID
FROM 
    Calibration
WHERE
    Telescope=${TELESCOPE}
ORDER BY
    NIGHT, RUNID\
"\
 |  mysql \
       --defaults-file=${CREDENTIALS} \
       --skip-column-names \
       --batch --raw \
       --compress \
 | \
while read -r -a LINE
do
  # Extract night/runid for data file and calibration file
  DATNIGHT=${LINE[0]}
  DATRUNID=${LINE[1]}
  DRSNIGHT=${LINE[2]}
  DRSRUNID=${LINE[3]}

  # Formatting of the file paths and names
  DATPATH=${DATNIGHT:0:4}/${DATNIGHT:4:2}/${DATNIGHT:6:2}
  DRSPATH=${DRSNIGHT:0:4}/${DRSNIGHT:4:2}/${DRSNIGHT:6:2}

  PREFIX=`printf ${DATNIGHT}_%03d ${DATRUNID}`

  DATNAME=`printf ${DATNIGHT}_%03d.fits.fz ${DATRUNID}`
  DRSNAME=`printf ${DRSNIGHT}_%03d.drs.fits ${DRSRUNID}`

  OUT=${DATA}/${CALLISTO}/${DATPATH}

  echo ""
  echo DAT=${DATNAME} [${DATPATH}]
  echo DRS=${DRSNAME} [${DRSPATH}]

  # Check if not yet successfully processed
  # Removing this file can be used to trigger a re-processing
  # the next time this script is executed
  if [ ! -f "${OUT}/.${PREFIX}.success" ]
  then

     cd ${MARS}

     mkdir -p ${OUT}

     # Trigger reprocessing of the process-fils in the star directory
     rm -f "${DATA}/${STAR}/${DATPATH}/.${PREFIX}.*"

     # Flag that a process is running
     rm ${OUT}/.${PREFIX}.done
     rm ${OUT}/.${PREFIX}.success

     touch ${OUT}/.${PREFIX}.running

     # Execute the calibration and write output to log-file
     root -b -q -l ${MACROS}/callisto.C'("'${DATA}/raw/${DATPATH}/${DATNAME}'","'${DATA}/raw/${DRSPATH}/${DRSNAME}'","'${OUT}'")' \
        2>&1 | tee ${OUT}/${PREFIX}.log

     RC=${PIPESTATUS[0]}

     # Remember exit status of callisto
     echo RC=${RC} | tee -a ${OUT}/${PREFIX}.log
     echo ${RC} > ${OUT}/.${PREFIX}.done

     # Processing is finished
     rm -f ${OUT}/.${PREFIX}.running

     # If processing was successfull write corresponding flag
     if [ "${RC}" == "0" ]
     then
         touch ${OUT}/.${PREFIX}.success
     fi

     cd -

  else
     echo Skipped.
  fi

done
