#/bin/bash

# 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=~/.password.cnf \
       --user=hawcwrite \
       --host=ihp-pc45.ethz.ch \
       --database=hawcdata \
       --skip-column-names \
       --batch --raw \
       --compress \
 | \
while IFS= read -r LINE
do

  # Get NIGHT and RUNID of all files
  NIGHT=`echo "$LINE" | awk -F"\t" '{print $1}'`
  RUNID=`echo "$LINE" | awk -F"\t" '{print $2}'`

  # Split into year, month, day
  YEAR=`echo ${NIGHT}  | cut -c1-4`
  MONTH=`echo ${NIGHT} | cut -c5-6`
  DAY=`echo ${NIGHT}   | cut -c7-8`

  # Format file and path names
  DIR="${BASEIN}/${YEAR}/${MONTH}/${DAY}"

  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.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