#!/bin/bash
#
# Starts thermostat storage (i.e. DB), attaches a
# local thermostat agent and opens up the
# thermostat gui (swing client).
#
#set -xv

function stop_agent() {
    if [ -e "${THERMOSTAT_AGENT_PID}" ]; then
        pid=$(cat "${THERMOSTAT_AGENT_PID}")
        kill ${pid}
        retval=$?
        # cleanup pid
        rm -rf "${THERMOSTAT_AGENT_PID}"
        return ${retval}
    else
        return 1
    fi
}

USER_THERMOSTAT_HOME=${HOME}/.thermostat
if [! -e ${USER_THERMOSTAT_HOME} ]; then
  mkdir -p ${USER_THERMOSTAT_HOME} 
fi
if [! -e ${USER_THERMOSTAT_HOME}/run ]; then
  mkdir ${USER_THERMOSTAT_HOME} 
fi

THERMOSTAT=/usr/share/thermostat/bin/thermostat
THERMOSTAT_AGENT_SCRIPT=/usr/share/thermostat
THERMOSTAT_AGENT_PID=${USER_THERMOSTAT_HOME}/run/thermostat-local-agent.pid

# Start storage
${THERMOSTAT} storage --start
# Start an agent in the background
${THERMOSTAT} -Tbg "${THERMOSTAT_AGENT_PID}" agent
# Start the gui; this blocks
${THERMOSTAT} gui

# This means gui finished, stop agent and storage
stop_agent
${THERMOSTAT} storage --stop
