#!/bin/ksh

#the master control file, shouldnt be cron accessible - they should be
#delegated through command file so checks can be performed

usage() {
    echo "Usage: $0 [--quiet] [--noreset] [--updatestate] [--updatetimerstate]" 1>&2
    exit 1
}

ac_currently_running() {
    # portable air conditioner draws 6 watts when in heating mode but
    # thermostat off.  Fans are running when in every other mode
    # regardless of thermostat
    power=$( timeout -k 1 10 curl -fsS --data-urlencode "cmnd=Status 8" http://ac-power/cm | sed 's/.*"Power":\([0-9.]*\)[^0-9.]*.*/\1/' )
    [ -n "$power" ] && [ "$power" -ge 5 ]
}

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

cmds_file=/tmp/ac.command-attempts

updatestate=
updatetimerstate=
reset=true
quiet=
while [ "$#" -gt 2 ] || [[ "$1" == --* ]] ; do
    case "$1" in
        --updatestate)
            updatestate=true
            shift
            ;;
        --updatetimerstate)
            updatetimerstate=true
            shift
            ;;
        --noreset)
            reset=
            shift
            ;;
        --quiet)
            quiet=--quiet
            shift
            ;;
        *)
            usage
            ;;
    esac
done

if [ "$#" -ne 0 ] ; then
    usage
fi

if [ $HOSTNAME != pi ] ; then
    exec ssh pi $0 "$@" < /dev/null
fi

# check last 3 invocations, and if all the same, don't keep running
# the same command (ie, give 3 attempts to get the command through the
# IR allowing for noise)
try_command() {
#    set -xv
    ( cat $cmds_file  ; echo "$@" ) | tail -n 4 > $cmds_file.tmp
    total_num=$( cat $cmds_file.tmp | wc -l )
    uniq_num=$( uniq $cmds_file.tmp | wc -l )
    if [ "$uniq_num" != 1 -o "$total_num" != 4 ] ; then
        timeout -k 1 10 curl -fsS "$@" || return
    fi
    mv $cmds_file.tmp $cmds_file
#    set +xv
}

# If we have heater socket at physical control panel wired so
# normally-closed, then heater can be disabled by unplugging at
# heater, or force enabled by powering off pi.  Useful girlfriend mode
# for if the pi fails while I'm out.  But if the pi fails while I'm
# out, the heater forces on.  No good when I'm the only occupant!

#turn_off_bit=
#grep -q ^ac $MODE_FILE && turn_off_bit=0
#grep -q ^heater $MODE_FILE && turn_off_bit=1
turn_off_bit=0

if [ -n "$reset" ] ; then
    check_ac --kill
    check_heater --kill
fi
#FIXME: improve servoing, and method of calling the controller - will have to differentiate between heat, cool, on, off and reached the thermostat (eg, set temperature just beyond where it currently is)
#GPIO=25
#gpio -g mode $GPIO out
#gpio -g write $GPIO $turn_off_bit

# portable AC
if ac_currently_running ; then
    timeout -k 1 10 curl -fsS --data-urlencode "cmnd=Power Off" http://ac-power/cm

    sleep 5
    # FIXME: when powers back on, portable air conditioner defaults to
    # AC-mode, power off.
    timeout -k 1 10 curl -fsS --data-urlencode "cmnd=Power On" http://ac-power/cm
fi
# check last 3 invocations, and if all the same, don't keep running the same command (ie, give 3 attempts to get the command through the IR allowing for noise)
if [ -n "$reset" ] ; then
    > $cmds_file
fi
# real AC, controllable through esp8266
#try_command http://ac/off
atomic_write --overwrite $THERMO_STATE_FILE "off # $date"
[ -n "$updatestate" ] && atomic_write --overwrite $STATE_FILE "off # $date"
[ -n "$updatetimerstate" -o -n "$reset" ] && atomic_write --overwrite $TIMER_STATE_FILE "disable # $date"
if [ -n "$reset" ] ; then
#    atomic_write --overwrite $DESIRED_STATE_FILE "off # $date"
# if we wanted to automatically reset the thermostat to the current
# value (because the user is happy with the current temp), this is how
# we'd do it.  But since we don't know that the user isn't just
# stepping outside, and wants the AC disabled right now, we don't do
# this automatically:
#        ac_thermostat_control set-thermostat-off `awk '{print $1}' $MODE_FILE`

    grep -q ^ac $MODE_FILE && check_ac $quiet
    grep -q ^heater $MODE_FILE && check_heater $quiet
fi
