#!/bin/sh

### BEGIN INIT INFO
# Provides:        logtide
# Required-Start:  $ntp
# Required-Stop:   
# Default-Start:   2 3 4 5
# Default-Stop:    0 1 6
# Short-Description: Start tide logging daemon
### END INIT INFO

# Derived from /etc/init.d/ntp on ubuntu 7.04

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/home/data/bin

. /lib/lsb/init-functions

NAME=logtide
#RUNASUSER=data
RUNASUSER=schwehr
DAEMON=/home/${RUNASUSER}/bin/serial-logger
PIDDIR=/var/run/data
PIDFILE=$PIDDIR/tide.pid
# Perhaps station should be /etc/station ?
# station names should be the state 2 letter prefix followed by a location code
STATION=nhjel

test -x $DAEMON || exit 5

#if [ -r /etc/default/$NAME ]; then
#	. /etc/default/$NAME
#fi

#if [ -e /etc/ntp.conf.dhcp ]; then
#	NTPD_OPTS="$NTPD_OPTS -c /etc/ntp.conf.dhcp"
#fi

UGID=$(getent passwd $RUNASUSER | cut -f 3,4 -d:) || true

case $1 in
	start)
		log_daemon_msg "Starting tide logging server" "logtide"
		if [ -z "$UGID" ]; then
			log_failure_msg "user \"$RUNASUSER\" does not exist"
			exit 1
		fi

		if [ ! -d $PIDDIR ]; then
		    mkdir -p $PIDDIR
		    chown $RUNASUSER $PIDDIR 
		fi
		# FIX: make this read through a list of loggers to run with parameters
		# How to control all of the loggers in batch or one at a time?
  		start-stop-daemon --start --quiet --oknodo --chdir /home/${RUNASUSER}/projects/data/tide --pidfile $PIDFILE --startas $DAEMON -c $RUNASUSER -- --pid-file $PIDFILE --baud=9600 -l tide-${STATION}- -p /dev/ttyS0 --daemon --uscg --station $STATION --timeout=300
		log_end_msg $?
  		;;
	stop)
		log_daemon_msg "Stopping tide logging server" "logtide"
  		start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE
		log_end_msg $?
		rm -f $PIDFILE
  		;;
	restart|force-reload)
		$0 stop && sleep 2 && $0 start
  		;;
	try-restart)
		if $0 status >/dev/null; then
			$0 restart
		else
			exit 0
		fi
		;;
	reload)
		exit 3
		;;
	status)
		# FIX: why does this not work?
		pidofproc -p $PIDFILE $DAEMON >/dev/null
		status=$?
		if [ $status -eq 0 ]; then
			log_success_msg "Tide logging server is running."
		else
			log_failure_msg "Tide logging server is not running."
		fi
		exit $status
		;;
	*)
		echo "Usage: $0 {start|stop|restart|try-restart|force-reload|status}"
		exit 2
		;;
esac
