#!/bin/sh
#
# weatherd       Starts the weather station service
#
# chkconfig:   345 05 95
# description:   1-Wire Weather Station Service
# ....
#
### BEGIN INIT INFO
# Provides:          weatherd
# Required-Start:    $all
# Required-Stop:     $all
# Default-Start:     3 4 5
# Default-Stop:      0 1 2 6
# Short-Description: Start weather daemon at boot time
# Description:       Enable weather service provided by daemon.
### END INIT INFO

WEATHER_HOME=/var/weather
CLASSPATH=$WEATHER_HOME/oneWireWeather.jar:$WEATHER_HOME/OneWireAPI.jar:$WEATHER_HOME/commons-configuration-1.6.jar:$WEATHER_HOME/commons-lang-2.6.jar:$WEATHER_HOME/commons-logging-1.1.1.jar:$WEATHER_HOME/commons-collections-3.2.1.jar:$WEATHER_HOME/postgresql-9.2-1000.jdbc4.jar

launch_daemon()
{
  /bin/sh <<EOF
  /usr/bin/java -Ddaemon.pidfile=/var/run/weather.pid -cp $CLASSPATH oneWireWeather.WeatherStationDaemon $WEATHER_HOME <&- &
  pid=\$!
  echo \$pid
EOF
}

start() {
echo -n "Starting weather station... "
cd /var/weather
daemon_pid=`launch_daemon`
if ps -p $daemon_pid >/dev/null 2>&1
then
  #daemon is running
  echo $daemon_pid >/var/run/weather.pid
  echo "done."
else
  echo "Daemon did not start."
fi
}

stop() {
echo -n "Stopping weather station... "
daemon_pid=`cat /var/run/weather.pid`
while ps -p $daemon_pid > /dev/null 2>&1
do
  kill $daemon_pid
  sleep 1
done
echo "done."
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        sleep 1
        start
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac

exit $RETVAL
