#!/bin/bash

NOW=$1

if [ -z "${NOW}" ]
then
    NOW=$(date +%H%M)
fi

if [ -z "${DEBUG}" ]
then
    DEBUG=0
fi

function runx()
{
    if [ ${DEBUG} -ne 0 ]
    then "$@"
    else "$@" > /dev/null 2>&1
    fi
    return $?
}

function debugx()
{
    if [ ${DEBUG} -ne 0 ]
    then echo "#" "$@"
    fi
}

function start_zeus()
{
    runx sudo /usr/sbin/etherwake -i eth1 00:24:8C:02:DD:2A
}

export PATH=/sbin:/usr/sbin:$HOME/bin:$PATH

runx check_availability.py
if [ $? -eq 0 ]
then AVAILABLE_NOW=1
else AVAILABLE_NOW=0
fi

debugx "Available: ${AVAILABLE_NOW}"

# Motion
if [ ${AVAILABLE_NOW} -eq 0 ]
then
    debugx "Starting motion"
    runx sudo /etc/init.d/motion start
else
    debugx "Stopping motion"
    runx sudo /etc/init.d/motion stop
fi

# Start Zeus
if [ ${NOW} = "0655" ] && [ ${AVAILABLE_NOW} -eq 1 ]
then
    debugx "(Morning) Checking availability in 2h30"
    if ! runx check_availability.py 9000
    then
	debugx "(Morning) Starting zeus"
	start_zeus
    else
	debugx "(Morning) Not starting zeus"
    fi
fi

if [ ${NOW} = "0900" ] && [ ${AVAILABLE_NOW} -eq 1 ]
then
    debugx "(Morning) Starting zeus"
    start_zeus
fi


if [ ${NOW} = "1830" ] && [ ${AVAILABLE_NOW} -eq 1 ]
then
    debugx "(Evening) Checking availability 30min ago"
    if ! runx check_availability.py -1800
    then
	debugx "(Evening) Starting zeus"
	start_zeus
    else
	debugx "(Evening) Not starting zeus"
    fi
fi

exit 0
