#!/bin/bash

EASY_VERSION="1.1"

bb=`tput bold`
nn=`tput sgr0`

# help
if [ $# -eq 0 ]; then
   echo "${bb}-------------------------------------------------------------------${nn}"
   echo "${bb}Creates sof-file for kmo_wave_cal-recipe and executes it.${nn}"
   echo " "
   echo "${bb}IMPORTANT:${nn} Files can be searched as well in folders from +/- 1 day!"
   echo "           (if toplevel directories are e.g. named YYYY-MM-DD)"
   echo " "
   echo "- The environment variable ${bb}KMOS_CALIB${nn} pointing to a path has to be"
   echo "  set in order to find the needed static calibration frames."
   echo "  Otherwise the execution of this script will fail!"
   echo "- If FLAT_EDGE, XCAL and YCAL frames aren't existing in"
   echo "  the working directory the script is searching as well KMOS_CALIB in"
   echo "  order to find them."
   echo "- As argument an arbitrary exposure of an executed "
   echo "  ${bb}KMOS_spec_cal_wave${nn} template must be provided."
   echo "  All matching exposures are collected automatically."
   echo "- (Optional) If as 2nd argument ${bb}sof${nn} is provided, then only"
   echo "  the sof-file is generated but not executed."
   echo " "
   echo "${bb}Usage:${nn}"
   echo "  easySPARK_wave_cal.sh <filename with full path>"
   echo "    or"
   echo "  easySPARK_wave_cal.sh <filename with full path> sof"
   echo " "
   echo "Version: "$EASY_VERSION
   echo "${bb}-------------------------------------------------------------------${nn}"
   exit
fi

# init
sofOnly=0
printVers=0

# extract all arguments beginning with KMOS, eventually imethod and sof
while [ "$1" ] ; do
    tmp=$(basename $1)
    if [[ $tmp == KMOS* ]]; then
        # file-check
        if [ ! -e $1 ]; then
            echo "${bb}ERROR:${nn} File doesn't exist! ($1)"
            exit
        fi
        fileName=$1
    else
        if [[ $tmp == sof ]]; then
            sofOnly=1
        elif [[ $tmp == vers ]]; then
            printVers=1
        fi
    fi
    shift
done

if [ $printVers = 1 ]; then
    echo $EASY_VERSION
    exit
fi

# check if gawk is existing
if command -v gawk >/dev/null; then
   :
else
    echo "'gawk' has not been found on your system!"
    OS=$(uname -s)
    if [ $OS != "Linux" ]; then
        echo "You seem using a MacOS, please use e.g. MacPorts to install gawk."
    fi
    echo "Aborting now.!"
fi

if [ -z "${KMOS_CALIB}" ]; then
    echo "ERROR: environment variable KMOS_CALIB is not defined! (see help)"
    exit
fi

#check if file is of correct template
tplId=$(dfits $fileName |\
        fitsort -d tpl.id |\
        gawk '{print $2}')
if [ $tplId != KMOS_spec_cal_wave ]; then
    echo "${bb}ERROR${nn}: File is of wrong template: $tplId instead of KMOS_spec_cal_wave !"
    exit
fi

# extract TPL.START of ths file
tplStartTime=$(dfits $fileName |\
               fitsort -d tpl.start |\
               gawk '{print $2}')

# analyze path, extract dates for today and yesterday            fileName:     # /<bla>/<blo>/2013-01-20/KMOS<xxx>
dataDir_today=$(dirname "$fileName")                                           # /<bla>/<blo>/2013-01-20
dataDir=${dataDir_today%/*}                                                    # /<bla>/<blo>/
today=${dataDir_today##*/}                                                     # 2013-01-20
matchingFiles=

date -d $today > /dev/null 2>&1
if [ $? = 0 ]; then
    # we have a directory like 2013-06-10
    yesterday=$(date --date=@$(( $(date --date=$today +%s) - 86400 )) +'%Y-%m-%d') # 2013-01-19
    dataDir_yesterday=$dataDir"/"$yesterday                                        # /<bla>/<blo>/2013-01-19
    tomorrow=$(date --date=@$(( $(date --date=$today +%s) + 86400 )) +'%Y-%m-%d')  # 2013-01-21
    dataDir_tomorrow=$dataDir"/"$tomorrow                                          # /<bla>/<blo>/2013-01-21

    # get all files with matching tplStartTime and ARC_OFF from yesterday
    matchingFiles_yesterday=
    if [ -e $dataDir_yesterday ]; then
        matchingFiles_yesterday=$(dfits $dataDir_yesterday/KMOS*.fits | \
                                  fitsort -d tpl.start dpr.type |\
                                  grep $tplStartTime |\
                                  grep WAVE,OFF |\
                                  gawk '{print $1}' |\
                                  tr "\n" " ")
    fi

    # get all files with matching tplStartTime and ARC_OFF from tomorrow
    matchingFiles_tomorrow=
    if [ -e $dataDir_tomorrow ]; then
        matchingFiles_tomorrow=$(dfits $dataDir_tomorrow/KMOS*.fits | \
                                 fitsort -d tpl.start dpr.type |\
                                 grep $tplStartTime |\
                                 grep WAVE,OFF |\
                                 gawk '{print $1}' |\
                                 tr "\n" " ")
    fi

    matchingFiles=$matchingFiles_yesterday$matchingFiles_tomorrow
fi

# get all files with matching tplStartTime and ARC_OFF from today
if [ -e $dataDir_today ]; then
    if ls $dataDir_today/KMOS*.fits &> /dev/null; then
        matchingFiles_today=$(dfits $dataDir_today/KMOS*.fits | \
                              fitsort -d tpl.start dpr.type |\
                              grep $tplStartTime |\
                              grep WAVE,OFF |\
                              gawk '{print $1}' |\
                              tr "\n" " ")
        matchingFiles=$matchingFiles$matchingFiles_today
    fi
fi

# populate sof-file with ARC_OFF frames
sofFile="wave_cal_$tplStartTime.sof"
cat > $sofFile </dev/null
for file in $matchingFiles; do
    echo "$file                ARC_OFF" >> $sofFile
done

# get all files with matching tplStartTime and ARC_ON from yesterday
matchingFiles=
matchingFiles_yesterday=
matchingFiles_tomorrow=
matchingFiles_today=
date -d $today > /dev/null 2>&1
if [ $? = 0 ]; then
    # we have a directory like 2013-06-10
    if [ -e $dataDir_yesterday ]; then
        matchingFiles_yesterday=$(dfits $dataDir_yesterday/KMOS*.fits | \
                                  fitsort -d tpl.start dpr.type |\
                                  grep $tplStartTime |\
                                  grep WAVE,LAMP |\
                                  gawk '{print $1}' |\
                                  tr "\n" " ")
    fi

    # get all files with matching tplStartTime and ARC_ON from tomorrow
    if [ -e $dataDir_tomorrow ]; then
        matchingFiles_tomorrow=$(dfits $dataDir_tomorrow/KMOS*.fits | \
                                 fitsort -d tpl.start dpr.type |\
                                 grep $tplStartTime |\
                                 grep WAVE,LAMP |\
                                 gawk '{print $1}' |\
                                 tr "\n" " ")
    fi

    matchingFiles=$matchingFiles_yesterday$matchingFiles_tomorrow
fi

# get all files with matching tplStartTime and ARC_ON from today
if [ -e $dataDir_today ]; then
    if ls $dataDir_today/KMOS*.fits &> /dev/null; then
        matchingFiles_today=$(dfits $dataDir_today/KMOS*.fits | \
                              fitsort -d tpl.start dpr.type |\
                              grep $tplStartTime |\
                              grep WAVE,LAMP |\
                              gawk '{print $1}' |\
                              tr "\n" " ")
        matchingFiles=$matchingFiles_$matchingFiles_today
    fi
fi

# populate sof-file with ARC_ON frames
for file in $matchingFiles; do
    echo "$file                ARC_ON" >> $sofFile
done

# get grating id of first ARC_ON frame
gratingUpper=$(dfits $matchingFiles |\
               fitsort -d ins.grat1.id |\
               head -n1 |\
               gawk '{print $2}')
gratingLower=$(echo $gratingUpper|tr "A-Z" "a-z")

# add static calibration frames
echo "$KMOS_CALIB/kmos_wave_ref_table.fits  REF_LINES" >> $sofFile
echo "$KMOS_CALIB/kmos_wave_band.fits       WAVE_BAND" >> $sofFile
echo "$KMOS_CALIB/kmos_ar_ne_list_$gratingLower.fits    ARC_LIST" >> $sofFile

# add band-specific calibration frames
fnFlatEdge=flat_edge_$gratingUpper$gratingUpper$gratingUpper.fits
fnXcal=xcal_$gratingUpper$gratingUpper$gratingUpper.fits
fnYcal=ycal_$gratingUpper$gratingUpper$gratingUpper.fits

if [ ! -e $fnFlatEdge ]; then
    fnFlatEdge=$KMOS_CALIB"/"$fnFlatEdge
fi
if [ ! -e $fnXcal ]; then
    fnXcal=$KMOS_CALIB"/"$fnXcal
fi
if [ ! -e $fnYcal ]; then
    fnYcal=$KMOS_CALIB"/"$fnYcal
fi
echo "$fnFlatEdge        FLAT_EDGE" >> $sofFile
echo "$fnXcal            XCAL" >> $sofFile
echo "$fnYcal            YCAL" >> $sofFile

echo ""
echo "${bb}-------------------- easySPARK_wave_cal -----------------------${nn}"
echo "${bb}INPUT${nn}"
echo "filename:  "$fileName
echo "with "
echo "TPL.START: "$tplStartTime
echo "GRATING:   "$gratingUpper
echo ""
echo "${bb}OUTPUT${nn}"
echo $sofFile" with:"
cat $sofFile
echo ""

# execute kmo_wave_cal
if [ $sofOnly = 0 ]; then
    echo "${bb}NOW CALCULATING WAVE CALIBRATION:${nn}"
    echo "esorex --suppress-prefix=TRUE kmo_wave_cal "$sofFile
   
    esorex --suppress-prefix=TRUE kmo_wave_cal $sofFile
fi
echo "${bb}----------------------------------------------------------${nn}"
