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

# Path where the data is stored... can be callisto or star
BASEIN=/data/callisto
# This is Y for calibrated data and I for image parameters
SUFFIX=Y
# The table to insert the data into (and create if not exists)
TABLE=Callisto
# Path to the executable
ROOT2SQL=~/FACT++/build/root2sql
# Resource file to use (should match the input files)
RESOURCE=root2sql-callisto.rc

# 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
FROM 
    Calibration_new
ORDER BY
    NIGHT, RUNID\

"\
 |  mysql \
       --defaults-file=${CREDENTIALS} \
       --skip-column-names \
       --batch --raw \
       --compress \
 | \
while read -r -a LINE
do
  # Get NIGHT and RUNID of all files
  NIGHT=${LINE[0]}
  RUNID=${LINE[1]}

  # Format file and path names
  DIR="${BASEIN}"/${NIGHT:0:4}/${NIGHT:4:2}/${NIGHT:6:2}

  PREFIX=`printf ${NIGHT}_%03d ${RUNID}`

  echo ""
  echo ${DIR}/${PREFIX}

  # Check if processing was successfull
  if [ -f ${DIR}/.${PREFIX}.success ]
  then

      ${ROOT2SQL} ${DIR}/${PREFIX}_${SUFFIX}Y.root \
         -C ${RESOURCE} \
         --table=${TABLE} \
         --const.Telescope=${TELESCOPE} \
         --const.NIGHT=${NIGHT} \
         --const.RUNID=${RUNID} \
         2>&1 | tee ${DIR}/${PREFIX}-root2sql.log

      echo RC=${PIPESTATUS[0]} >> ${DIR}/${PREFIX}-root2sql.log
   else
      echo Skipped.
   fi

done
