#!/bin/ksh

RUN_DIR=$(cd -- "$(dirname "$0")" && pwd)
PATH=$RUN_DIR:/usr/local/bin/:$PATH ; export PATH
. ac_common

HYSTERESIS=0.3
# how much to subtract from the offset while I cool down after a ride
# coming home - starting 1 degree then increasing up to temp over half
# an hour?
ramp_max_offset=3.5
ramp_offset_duration=1800

calc_rampup_offset() {
    ramp_offset_start=$(atomic_read --no-rm "$THERMO_STARTRAMP_FILE")
    if [ "$setpoint_file_time" -le "$ramp_offset_start" ] && 
        # if user has adjusted setpoint themselves, then assume they
        # no longer want a ramp for now.
        [ $(bc -l <<< "$time-$ramp_offset_start") -lt "$ramp_offset_duration" ] ; then
        rampup_offset=$(bc -l <<< "scale=2; $ramp_max_offset*(1-($time-$ramp_offset_start)/$ramp_offset_duration)")
    else
        rampup_offset=0
    fi
    echo $rampup_offset
}

status() {
    # only output status when we aren't in the process of being asked
    # to set limits based on current value.  Be silent otherwise,
    # since we'll be asked very soon to redisplay our new values
    if [ -z "$set_thermo_on$set_thermo_off" ] ; then
        echo "$@"
    fi
}

date=$(date)
time=$(date +%s)

set_thermo_on=
set_thermo_off=

control="$1"
if [ "$control" = set-thermostat-on ] ; then
    control=on
    set_thermo_on=1
elif [ "$control" = set-thermostat-off ] ; then
    control=off
    set_thermo_off=1
fi
running_mode="$2"
THERMOSTAT_CONTROL_FILE="/var/tmp/ac.thermostat.${running_mode}"

if [ ! -e "$THERMOSTAT_CONTROL_FILE" ] ; then
    turn_${control}_ac --noreset
else
    setpoint_file_time=$(stat -c %Y "$THERMOSTAT_CONTROL_FILE")
    setpoint=$(atomic_read --no-rm "$THERMOSTAT_CONTROL_FILE")
    rampup_offset=$(calc_rampup_offset)
    setpoint=$(bc -l <<< "$setpoint-$rampup_offset")
    atomic_write --overwrite "$THERMO_SETPOINT_FILE" "$setpoint"

    study_temp=$(atomic_read --no-rm $STUDY_TEMP_FILE)
    upper_setpoint=$(bc -l <<< "$setpoint+$HYSTERESIS") # enough inertia in the system we can use 0.0 - in fact we'd rather it be negative when forcing up/down to temperature
    lower_setpoint=$(bc -l <<< "$setpoint-$HYSTERESIS") # enough inertia in the system we can use 0.0
    study_temp=$(bc -l <<< "$study_temp")

    status "upper_setpoint=$upper_setpoint; lower_setpoint=$lower_setpoint; study_temp=$study_temp"
    if [ -z "$study_temp" ] ; then
                #safety first
        turn_off_ac --noreset
        exit
    fi

    temp_above_upper_threshold=$(bc -l <<< "$study_temp >= $upper_setpoint")
    temp_below_upper_threshold=$(bc -l <<< "$study_temp <  $upper_setpoint")
    temp_below_lower_threshold=$(bc -l <<< "$study_temp <= $lower_setpoint")
    temp_above_lower_threshold=$(bc -l <<< "$study_temp >  $lower_setpoint")

    temp_below_off_ac_threshold=$(    bc -l <<< "$study_temp <= ($lower_setpoint-4)")
    temp_above_off_heater_threshold=$(bc -l <<< "$study_temp >= ($upper_setpoint+4)")
    setpoint_plus_2=$(                printf "%.0f" $( bc -l <<< "$setpoint + 2"))
    setpoint_plus_1=$(                printf "%.0f" $( bc -l <<< "$setpoint + 1"))
    setpoint_minus_2=$(               printf "%.0f" $( bc -l <<< "$setpoint - 2"))
    setpoint_minus_1=$(               printf "%.0f" $( bc -l <<< "$setpoint - 1"))

    status "temp_above_upper_threshold=$temp_above_upper_threshold; temp_below_lower_threshold=$temp_below_lower_threshold"

    case "${running_mode}" in
        ac)
            if [ -n "$set_thermo_on$set_thermo_off" ] ; then
                if [ $temp_below_upper_threshold = 1 -a -n "$set_thermo_on" ] ; then
                    echo "Resetting threshold to $study_temp to force on"
                    atomic_write --overwrite "$THERMOSTAT_CONTROL_FILE" "$(bc -l <<< "$study_temp-$HYSTERESIS")"
                    temp_above_upper_threshold=1
                    temp_below_lower_threshold=0
                elif [ $temp_above_lower_threshold = 1 -a -n "$set_thermo_off" ] ; then
                    echo "Resetting threshold to $study_temp to force off"
                    atomic_write --overwrite "$THERMOSTAT_CONTROL_FILE"  "$(bc -l <<< "$study_temp+$HYSTERESIS")"
                    temp_above_upper_threshold=0
                    temp_below_lower_threshold=1
                fi
            fi
            if [ "$control" = off ] ; then
                status "Asked to turn off AC ($date)"
                turn_off_ac --noreset
            elif [ $temp_below_off_ac_threshold = 1 ] ; then
                status "Turning AC off due to thermostat ($date)"
                turn_off_ac --noreset
            elif [ $temp_above_upper_threshold = 1 ] ; then
                status "Turning AC on due to thermostat ($date)"
                turn_on_ac --noreset --thermo $setpoint_minus_2
            elif [ $temp_below_lower_threshold = 1 ] ; then
                status "Turning AC down due to thermostat ($date)"
                turn_on_ac --noreset --thermo $setpoint_plus_1
            else 
#                turn_on_ac --noreset --thermo $setpoint
                status "Keeping AC in current state since in thermostat deadband ($date)"
                touch $THERMO_STATE_FILE  # keep the watchdog happy
            fi
            ;;
        heater)
            if [ -n "$set_thermo_on$set_thermo_off" ] ; then
                if [ $temp_above_lower_threshold = 1 -a -n "$set_thermo_on" ] ; then
                    status "Resetting threshold to $study_temp to force on"
                    atomic_write --overwrite "$THERMOSTAT_CONTROL_FILE"  "$(bc -l <<< "$study_temp+$HYSTERESIS")"
                    temp_below_lower_threshold=1
                    temp_above_upper_threshold=0
                elif [ $temp_below_upper_threshold = 1 -a -n "$set_thermo_off" ] ; then
                    status "Resetting threshold to $study_temp to force off"
                    atomic_write --overwrite "$THERMOSTAT_CONTROL_FILE"  "$(bc -l <<< "$study_temp-$HYSTERESIS")"
                    temp_below_lower_threshold=0
                    temp_above_upper_threshold=1
                fi
            fi
            if [ "$control" = off ] ; then
                status "Asked to turn off heater ($date)"
                turn_off_ac --noreset
            elif [ $temp_above_off_heater_threshold = 1 ] ; then
                status "Turning heater off due to thermostat ($date)"
                turn_off_ac --noreset
            elif [ $temp_below_lower_threshold = 1 ] ; then
                status "Turning heater on due to thermostat ($date)"
                turn_on_ac --noreset --thermo $setpoint_plus_1
            elif [ $temp_above_upper_threshold = 1 ] ; then
                status "Turning heater down due to thermostat ($date)"
                turn_on_ac --noreset --thermo $setpoint_minus_2
            else 
 #               turn_on_ac --noreset --thermo $setpoint
                status "Keeping heater in current state since in thermostat deadband ($date)"
                touch $THERMO_STATE_FILE  # keep the watchdog happy
            fi
            ;;
    esac
fi
