#!/bin/bash

#set -x

HOME=${HOME:-/var/home/pi}
MY_DIR=$( dirname "$0" )
ENV_FILE="${0}.env"
LOG_FILE="${1:-$HOME/minigc.log}"
# Define the lock file path
LOCKFILE="${MY_DIR}/.minGC.lock"
RUN_DIR="/run/miniGC_rt"
SERVICE_CTL=/etc/init.d/recordum-minigc
SERVICE_STATE="${RUN_DIR}/recordum-minigc.enabled"

## Make sure the run dir exists
if [ ! -d "${RUN_DIR}" ]; then
    if ! mkdir "${RUN_DIR}" 2>&1; then
        echo "Error!  Could not create run dir ${RUN_DIR}"
        exit 1
    fi
fi

## Set up the GNUPLOT Binary.
if ! GNUPLOT=$( which gnuplot 2>/dev/null ); then
    GNUPLOT=/usr/bin/gnuplot
fi

if [ ! -e "${ENV_FILE}" ]; then
    ## first load the env file.  We keep things secure by doing this FIRST
    ## so that we can override anything that needs to be set in the script.
    echo "Error! Environment file not found.  Bailing out."
    exit 1
fi
source "${ENV_FILE}"

require_minigc_service() {
    if ${SERVICE_CTL} status >/dev/null 2>&1; then
        return 0
    fi
    if [ ! -f "${SERVICE_STATE}" ]; then
        echo "recordum-minigc service is disabled. Run miniGC_enable to re-enable it."
        exit 1
    fi

    echo "recordum-minigc service is not running; attempting restart..."
    local restart_rc=1
    if [ "$(id -u)" -eq 0 ]; then
        ${SERVICE_CTL} restart >/dev/null 2>&1
        restart_rc=$?
    else
        sudo -n ${SERVICE_CTL} restart >/dev/null 2>&1
        restart_rc=$?
    fi
    if [ ${restart_rc} -eq 0 ]; then
        sleep 2
        if ${SERVICE_CTL} status >/dev/null 2>&1; then
            return 0
        fi
    fi
    echo "Error! recordum-minigc service is disabled or failed to start."
    exit 1
}

require_minigc_service

## Variable declarations / Overrides
MISURE_DIR="$HOME/misure"
DAILYDIR="${MISURE_DIR}/$(date +%Y-%m-%d)"
IFS=":" read -r SERIAL_PORT _SERIAL_TARGET <<<"${settings_serial_port_text:-/dev/ttyUSB0}"
# SERIAL_SPEC="${settings_serial_port_text:-/dev/ttyUSB0}"
# SERIAL_PORT="${SERIAL_SPEC%%:*}"
# SERIAL_TARGET=""

(
    TMP_LOG=$( mktemp )

    finalize() {
        local exit_code=$1
        trap - EXIT INT TERM HUP
        if [ "${LOG_FILE}" != - ] && [ -n "${TMP_LOG}" ] && [ -f "${TMP_LOG}" ]; then
            cp "${TMP_LOG}" "${LOG_FILE}"
        fi
        rm -f "${TMP_LOG}"
        exit "${exit_code}"
    }

    trap 'finalize $?' EXIT
    trap 'finalize 130' INT
    trap 'finalize 143' TERM
    trap 'finalize 129' HUP

    if [ "${LOG_FILE}" != - ]; then
        exec &>"${TMP_LOG}"
    fi

    cd ${MY_DIR}
    exec 200> $LOCKFILE
    # Try to get the lock. Exit with error if unsuccessful.
    WAITED=30
    while ! flock -n 200; do
        echo "Lock held by another process. Exiting in $WAITED seconds."
        sleep 1
        WAITED=$[WAITED - 1]
        if [ "$WAITED" -le 0 ]; then
           echo "Done waiting.  We lost a measurement cycle."
           exit 1
        fi
    done

	# this actually lunches the miniGC acquisition cycle
	METHOD_FILE="${settings_seq_file_text:-real.seq}"
	if [ "${METHOD_FILE#/}" != "${METHOD_FILE}" ]; then
		METHOD_PATH="${METHOD_FILE}"
	else
		METHOD_PATH="${MY_DIR}/${METHOD_FILE}"
	fi
	if [ ! -f "${METHOD_PATH}" ]; then
		echo "Error! Method file '${METHOD_FILE}' not found at ${METHOD_PATH}. MiniGC cannot run."
		exit 1
	fi

	MINIGC_PARAMS=(
		-GCport "${SERIAL_PORT}"
		-method "${METHOD_FILE}"
		-root "${MISURE_DIR}"
		-cycle "${settings_cycle_seconds:-900}"
		-PIDdelay "${settings_pid_delay_seconds:-60}"
        -PIDcycle "${settings_pid_cycle_seconds:-800}"
        -PIDgain "${settings_gain_nounit:-4}"
        -dailysub  -silent -runtimedump
        -samplevolume "${settings_sample_volume_nounit:-1100}"
    )

    {
       echo "******************************** $( date ) *********************************"
       echo ${MY_DIR}/miniGC "${MINIGC_PARAMS[@]}"
    } | if [ "${LOG_FILE}" != - ]; then
        tee -a "${LOG_FILE}"
    else
       cat
    fi
    ${MY_DIR}/miniGC "${MINIGC_PARAMS[@]}"
    EXIT_CODE="$?"

    if [ "${EXIT_CODE}" -ne 0 ]; then
        echo "Error!  miniGC command exited with status ${EXIT_CODE}"
        exit 1
    fi

    # call the processor binary to calculate peak heights using command line parameters from last calibration.
    LASTFILE=$(ls -1 ${DAILYDIR}/PID*.dat | tail -n 1)

    if [ ! -f "${LASTFILE}" ]; then
        echo "Error! No output produced - bailing out early."
        exit 1
    fi

    PROC_PARS=""
    if [ -d "$HOME/calParams" ]; then
        for f in $HOME/calParams/*ProcPars.txt; do
            PROC_PARS="$PROC_PARS $(cat $f)"
        done
    fi

    PROC_PARAMS=(
        "${LASTFILE}"
        benzene "${benzene_start_seconds}" "${benzene_end_seconds}" "${benzene_width_seconds}" "${benzene_maxpos_seconds}" "${benzene_maxwidth_seconds}"
        toluene "${toluene_start_seconds}" "${toluene_end_seconds}" "${toluene_width_seconds}" "${toluene_maxpos_seconds}" "${toluene_maxwidth_seconds}"
        ethylbenzene "${ethylbenzene_start_seconds}" "${ethylbenzene_end_seconds}" "${ethylbenzene_width_seconds}" "${ethylbenzene_maxpos_seconds}" "${ethylbenzene_maxwidth_seconds}"
        xylene "${xylene_start_seconds}" "${xylene_end_seconds}" "${xylene_width_seconds}" "${xylene_maxpos_seconds}" "${xylene_maxwidth_seconds}"
        ${PROC_PARS}
    )

    # do all the plots, and destroy unneeded files
    #plot chromatogram
    DATA_FILE=$(mktemp)
    CMD=( "${MY_DIR}/processor" "${PROC_PARAMS[@]}" )
    echo Executing "${CMD[@]}"
    "${CMD[@]}" > "${DATA_FILE}"
    CMD=( ${GNUPLOT} -e "file_to_plot='${DATA_FILE}'" "${MY_DIR}/gnuplot_script" )
    echo Executing "${CMD[@]}"
    "${CMD[@]}" > "${LASTFILE}.png"
    rm "${DATA_FILE}"

    for compound in benzene toluene ethylbenzene xylene; do
        DATA_FILE="${DAILYDIR}/${compound}"
        SENSITIVITY="" ## "$( cat sensB )" - Not used
        if [ -f "${DATA_FILE}" ]; then
            CMD=( ${GNUPLOT} -e "compound='${DATA_FILE}'" -e "sensitivity='${SENSITIVITY}'" "${MY_DIR}/gnuplot_script_daily" )
            echo Executing "${CMD[@]}"
            "${CMD[@]}"> "${DATA_FILE}.png"
        fi
    done

)

exit 0
