#!/bin/bash

HAS_VALVE=0
if gpioinfo 2>/dev/null | grep -q valve-actuate; then
	HAS_VALVE=1
fi

function cleanup {
	echo "Stopping PC..."
	timeout 0.25 gpioset pc-power-button=1
	timeout 0.25 gpioset pc-power-button=0
	sleep 10
	killall gpioset
	CLEANUP_GPIOS="water-pump=0 coolant-pump=0 pc-contactor=0"
	if [ "$HAS_VALVE" = "1" ]; then
		CLEANUP_GPIOS="$CLEANUP_GPIOS valve-actuate=0"
	fi
	timeout 0.25 gpioset $CLEANUP_GPIOS
	echo "Done"
}

trap cleanup EXIT

RC="$HOME/.watter-screenrc"

cat > $RC << EOF
# Turn on hardstatus at bottom
hardstatus on
hardstatus alwayslastline

# Check host every 10 seconds
backtick 1 0 0 watter-check-pc-up

# Status line format
hardstatus string " Host: pc-watter | Status: %1\` | %H | %c | Ctrl+D to exit and stop PC"

startup_message off
EOF

echo "Starting PC..."
GPIOS="water-pump=1 coolant-pump=1 pc-contactor=1"
if [ "$HAS_VALVE" = "1" ]; then
	GPIOS="$GPIOS valve-actuate=1"
fi
gpioset -z $GPIOS
sleep 2
timeout 0.25 gpioset pc-power-button=1
timeout 0.25 gpioset pc-power-button=0

screen -c $RC

rm -f $RC
