#! /bin/sh
### BEGIN INIT INFO
# Provides:          wfrog
# Required-Start:    $local_fs $remote_fs
# Required-Stop:     $local_fs $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: wfrog
# Description:       wfrog - Weather Station Software
### END INIT INFO

# Author: Laurent bovet <laurent.bovet@windmaster.ch>, mennucc1@debian.org
# Do NOT "set -e"

# PATH should only include /usr/* if it runs after the mountnfs.sh script

PATH=/usr/sbin:/usr/bin:/sbin:/bin
NAME=wfrog
DESC="wfrog program - Weather Station Software "
PROGRAM_DIR=/usr/lib/wfrog/bin
PROGRAM=wfrog
PROGRAM_ARGS=""
PIDFILE_PROGRAM=/var/run/wfrog.pid
SCRIPTNAME=/etc/init.d/wfrog
USER=root

# Exit if the package is not installed
[ -x "$PROGRAM_DIR/$PROGRAM" ] || exit 0

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

# Load the VERBOSE setting and other rcS variables
[ -f /etc/default/rcS ] && . /etc/default/rcS

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

#
# Function that starts the daemon/service
#
do_start_program()
{
    # Return
    #   0 if daemon has been started
    #   1 if daemon was already running
    #   2 if daemon could not be started
    start-stop-daemon --start --quiet --background --make-pidfile --pidfile $PIDFILE_PROGRAM -d $PROGRAM_DIR --exec $PROGRAM_DIR/$PROGRAM --test > /dev/null \
        || return 1
    start-stop-daemon --start  --background --make-pidfile --pidfile $PIDFILE_PROGRAM -d $PROGRAM_DIR --exec $PROGRAM_DIR/$PROGRAM -- $PROGRAM_ARGS  \
        || return 2
}


#
# Function that stops the daemon/service
#
do_stop_program()
{
    # Return
    #   0 if daemon has been stopped
    #   1 if daemon was already stopped
    #   2 if daemon could not be stopped
    #   other if a failure occurred
    start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE_PROGRAM --name $PROGRAM
    RETVAL="$?"
    [ "$RETVAL" = 2 ] && return 2
    rm -f $PIDFILE
    return "$RETVAL"
}

case "$1" in
  start)
    if test ! -f /etc/wfrog/settings.yaml -o ! -s  /etc/wfrog/settings.yaml ; then
     log_warning_msg "Please call 'wfrog -S' to create the configuration file"
    else
     log_daemon_msg "Starting $DESC" "$NAME"
     do_start_program
     log_end_msg  $?
    fi
    ;;
  stop)
    log_daemon_msg "Stopping $DESC" "$NAME"
    do_stop_program
    log_end_msg  $?
    ;;
  restart|force-reload)
    #
    # If the "reload" option is implemented then remove the
    # 'force-reload' alias
    #
    log_daemon_msg "Restarting $DESC" "$NAME"
    do_stop_program
    do_start_program
    log_end_msg  $?
    ;;
  *)
    #echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
    echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
    exit 3
    ;;
esac

:
