#!/bin/bash -e

# TODO: This is hardcoded...
CONTROLLER="10.41.61.10"
ONFILE="/tmp/sprinklers-lock"

MASTERVALVE="4"
LAWNVALVE="0"
FRONTVALVE="1"
BACKVALVE="2"

function valveon {
	wget -O /dev/null -o /dev/null http://$CONTROLLER/ioval.cgi?B$1=0
}
function valveoff {
	wget -O /dev/null -o /dev/null http://$CONTROLLER/ioval.cgi?B$1=1
}

: ${1?"Usage: $0 <area> <on|off> Areas: lawn, backgarden, frontgarden"}

if [ "$1" = "clean" ];
then
	valveoff $MASTERVALVE
	valveoff $FRONTVALVE
	valveoff $BACKVALVE
	valveoff $LAWNVALVE
	rm -f $ONFILE
fi

echo -n "Turning "
echo -n "$1"
echo "$2"

if [[ "$1" = "lawn" || "$1" == "backgarden" || "$1" == "frontgarden" ]];
then
	if [ "$1" = "lawn" ];
	then
		THISVALVE="$LAWNVALVE"
	fi
	if [ "$1" = "backgarden" ];
	then
		THISVALVE="$BACKVALVE"
	fi
	if [ "$1" = "frontgarden" ];
	then
		THISVALVE="$FRONTVALVE"
	fi

	if [ "$2" = "on" ];
	then
		if [ ! -e "$ONFILE" ];
		then
			echo "$1" > "$ONFILE"
			valveon $THISVALVE
			valveon $MASTERVALVE
		else
			echo "Sprinklers already on!"
			echo "Try with 'clean'"
		fi
	else
		valveoff $MASTERVALVE off
		valveoff $FRONTVALVE off
		valveoff $BACKVALVE off
		valveoff $LAWNVALVE off
		rm -f "$ONFILE"
	fi
else
	echo "Invalid area name."
fi

