#!/bin/bash

# The base directory of the aux-files
AUX=/home/tbretz/data/aux
# The Mars build directory
MARS=~/Mars/build
# The path (relative to your Mars/build directory where the processing macros are stored
MACROS=../hawc/processing

# Open the query-file with the create table statement
echo \
"\
CREATE TABLE AuxData
(
   NIGHT           INT       UNSIGNED  NOT NULL,
   RUNID           MEDIUMINT UNSIGNED  NOT NULL,
   TavgDRS         FLOAT,
   TrmsDRS         FLOAT,
   Umed            FLOAT,
   Uavg            FLOAT,
   Udev            FLOAT,
   Urms            FLOAT,
   Imed            FLOAT,
   Iavg            FLOAT,
   Idev            FLOAT,
   Irms            FLOAT,
   Tmed            FLOAT,
   Tavg            FLOAT,
   Tdev            FLOAT,
   Trms            FLOAT,
   TavgPSU         FLOAT,
   TotalOnTime     FLOAT,
   TotalDeadTime   FLOAT,
   TavgFTM         FLOAT,
   ThresholdChMin  MEDIUMINT UNSIGNED,
   ThresholdChMed  FLOAT,
   ThresholdChMax  MEDIUMINT UNSIGNED,
   ThresholdSumMin MEDIUMINT UNSIGNED,
   ThresholdSumMax MEDIUMINT UNSIGNED,
   RateCh0         FLOAT,
   RateCh1         FLOAT,
   RateCh2         FLOAT,
   RateCh3         FLOAT,
   RateCh4         FLOAT,
   RateCh5         FLOAT,
   RateCh6         FLOAT,
   RateCh7         FLOAT,
   RateSum0        FLOAT,
   RateSum1        FLOAT,
   PRIMARY KEY(NIGHT, RUNID)
) 
SELECT * FROM 
( VALUES
"\ > insert-data.sql

# Get all available runs and their start and stop time
# note that no check is done on the stop time!
echo \
"\
SELECT 
    NIGHT, RUNID, TSTARTI+TSTARTF, TSTOPI+TSTOPF
FROM 
    RawData\
"\
 |  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

  # Extract night, runid, begin and end
  NIGHT=`echo "$LINE" | awk -F"\t" '{print $1}'`
  RUNID=`echo "$LINE" | awk -F"\t" '{print $2}'`
  BEG=`echo   "$LINE" | awk -F"\t" '{print $3}'`
  END=`echo   "$LINE" | awk -F"\t" '{print $4}'`

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

  # Base path for the night
  FNAME=${AUX}/${YEAR}/${MONTH}/${DAY}/${NIGHT}

  echo ""
  echo ${FNAME}

  cd ${MARS}

  # Return corresponding data for DRS temperatures from FAD_CONTROL_TEMPEREATURE
  RESULT=`root -b -q -l '${MACROS}/drstemp.C("'${FNAME}'.FAD_CONTROL_TEMPERATURE.fits",'${BEG}','${END}')' | grep result`
  if [ -n "${RESULT}" ]
  then
     TEMP_AVG=`echo ${RESULT} | cut -f2 -d' '`
     TEMP_RMS=`echo ${RESULT} | cut -f4 -d' '`
  else
     TEMP_AVG="NULL"
     TEMP_RMS="NULL"
  fi
  echo ${RESULT}

  # Return corresponding data for currents from BIAS_CONTROL_DYNAMIC_DATA
  RESULT=`root -b -q -l '${MACROS}/currents.C("'${FNAME}'.BIAS_CONTROL_DYNAMIC_DATA.fits",'${BEG}','${END}')' | grep result`
  if [ -n "${RESULT}" ]
  then  
     BIAS_UMED=`echo ${RESULT} | cut -f2  -d' '`
     BIAS_UAVG=`echo ${RESULT} | cut -f3  -d' '`
     BIAS_UDEV=`echo ${RESULT} | cut -f4  -d' '`
     BIAS_URMS=`echo ${RESULT} | cut -f5  -d' '`
     BIAS_IMED=`echo ${RESULT} | cut -f6  -d' '`
     BIAS_IAVG=`echo ${RESULT} | cut -f7  -d' '`
     BIAS_IDEV=`echo ${RESULT} | cut -f8  -d' '`
     BIAS_IRMS=`echo ${RESULT} | cut -f9  -d' '`
     BIAS_TMED=`echo ${RESULT} | cut -f10 -d' '`
     BIAS_TAVG=`echo ${RESULT} | cut -f11 -d' '`
     BIAS_TDEV=`echo ${RESULT} | cut -f12 -d' '`
     BIAS_TRMS=`echo ${RESULT} | cut -f13 -d' '`
     BIAS_PSU=`echo  ${RESULT} | cut -f14 -d' '`
  else
     BIAS_UMED="NULL"
     BIAS_UAVG="NULL"
     BIAS_UDEV="NULL"
     BIAS_URMS="NULL"
     BIAS_IMED="NULL"
     BIAS_IAVG="NULL"
     BIAS_IDEV="NULL"
     BIAS_IRMS="NULL"
     BIAS_TMED="NULL"
     BIAS_TAVG="NULL"
     BIAS_TDEV="NULL"
     BIAS_TRMS="NULL"
     BIAS_PSU="NULL"
  fi
  echo ${RESULT}

  # Return corresponding data for trigger information from FTM_CONTROL_DATA
  RESULT=`root -b -q -l '${MACROS}/trigger.C("'${FNAME}'.FTM_CONTROL_DATA.fits",'${BEG}','${END}')' | grep result`
  if [ -n "${RESULT}" ]
  then
     TOT_TIME=`echo ${RESULT} | cut -f2 -d' '`
     TOT_DEAD=`echo ${RESULT} | cut -f3 -d' '`
     EFF=`echo      ${RESULT} | cut -f4 -d' '`
     TM_AVG=`echo   ${RESULT} | cut -f5 -d' '`
  else
     TOT_TIME="NULL"
     TOT_DEAD="NULL"
     EFF="NULL"
     TM_AVG="NULL"
  fi
  echo ${RESULT}

  # Return corresponding data for threshold seeting from FTU_CONTROL_DATA
  RESULT=`root -b -q -l '${MACROS}/threshold.C("'${FNAME}'.FTU_CONTROL_DATA.fits",'${BEG}','${END}')' | grep result`
  if [ -n "${RESULT}" ]
  then
     DAC_CH_MIN=`echo  ${RESULT} | cut -f2  -d' '`
     DAC_CH_MED=`echo  ${RESULT} | cut -f3  -d' '`
     DAC_CH_MAX=`echo  ${RESULT} | cut -f4  -d' '`
     DAC_SUM_MIN=`echo ${RESULT} | cut -f5  -d' '`
     DAC_SUM_MAX=`echo ${RESULT} | cut -f6  -d' '`
     RATE_CH1=`echo    ${RESULT} | cut -f7  -d' '`
     RATE_CH2=`echo    ${RESULT} | cut -f8  -d' '`
     RATE_CH3=`echo    ${RESULT} | cut -f9  -d' '`
     RATE_CH4=`echo    ${RESULT} | cut -f10 -d' '`
     RATE_CH5=`echo    ${RESULT} | cut -f11 -d' '`
     RATE_CH6=`echo    ${RESULT} | cut -f12 -d' '`
     RATE_CH7=`echo    ${RESULT} | cut -f13 -d' '`
     RATE_CH8=`echo    ${RESULT} | cut -f14 -d' '`
     RATE_SUM1=`echo   ${RESULT} | cut -f15 -d' '`
     RATE_SUM2=`echo   ${RESULT} | cut -f16 -d' '`
  else
     DAC_CH_MIN="NULL"
     DAC_CH_MED="NULL"
     DAC_CH_MAX="NULL"
     DAC_SUM_MIN="NULL"
     DAC_SUM_MAX="NULL"
     RATE_CH1="NULL"
     RATE_CH2="NULL"
     RATE_CH3="NULL"
     RATE_CH4="NULL"
     RATE_CH5="NULL"
     RATE_CH6="NULL"
     RATE_CH7="NULL"
     RATE_CH8="NULL"
     RATE_SUM1="NULL"
     RATE_SUM2="NULL"
  fi
  echo ${RESULT}

  cd -

  # Write the result as one row to the query file
  echo "/* "${FNAME}" */" >> insert-data.sql
  echo "ROW(" >> insert-data.sql
  echo " "${NIGHT}, ${RUNID}, >> insert-data.sql
  echo " "${TEMP_AVG}, ${TEMP_RMS}, >> insert-data.sql
  echo " "\
     ${BIAS_UMED}, ${BIAS_UAVG}, ${BIAS_UDEV}, ${BIAS_URMS}, \
     ${BIAS_IMED}, ${BIAS_IAVG}, ${BIAS_IDEV}, ${BIAS_IRMS}, \
     ${BIAS_TMED}, ${BIAS_TAVG}, ${BIAS_TDEV}, ${BIAS_TRMS}, \
     ${BIAS_PSU},  >> insert-data.sql
  echo " "${TOT_TIME}, ${TOT_DEAD}, ${EFF}, ${TM_AVG},  >> insert-data.sql
  echo " "\
     ${DAC_CH_MIN}, ${DAC_CH_MED}, ${DAC_CH_MAX}, ${DAC_SUM_MIN}, ${DAC_SUM_MAX}, \
     ${RATE_CH1}, ${RATE_CH2}, ${RATE_CH3}, ${RATE_CH4}, ${RATE_CH5}, ${RATE_CH6}, ${RATE_CH7}, ${RATE_CH8}, \
     ${RATE_SUM1}, ${RATE_SUM2} >> insert-data.sql
  echo ")," >> insert-data.sql

done

# Finish the query file with defining the column names
echo "\
AS
(
   NIGHT, RUNID,
   TavgDRS, TrmsDRS,
   Umed, Uavg, Udev, Urms,
   Imed, Iavg, Idev, Irms,
   Tmed, Tavg, Tdev, Trms,
   TavgPSU,
   TotalOnTime, TotalDeadTime, Efficiency, TavgFTM,
   ThresholdChMin, ThresholdChMed, ThresholdChMax, 
   ThresholdSumMin, ThresholdSumMax, 
   RateCh0, RateCh1, RateCh2, RateCh3, RateCh4, RateCh5, RateCh6, RateCh7,
   RateSum0, RateSum1
)\ 
" >> insert-data.sql