#! /bin/sh
### BEGIN INIT INFO
# Provides:          pianod
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Starts pianod
# Description:       pianod is a clent/server for Pandora.  This init script
#                    copied and repurposed from RasPi init.d/lirc
### END INIT INFO

# Load functions
. /lib/lsb/init-functions

# Load config file if exists
CONFIGFILE=/etc/pianod.conf
if [ -f "$CONFIGFILE" ]; then
  . "$CONFIGFILE"
fi

# Use value set by config file or else defaults
DAEMON=${DAEMON:-/usr/sbin/pianod}
test -f $DAEMON || exit 0

case "$1" in
  start)
    log_daemon_msg "Starting pianod"

    # Load param from config file or else use default
    STARTSCRIPT=${STARTSCRIPT:-/etc/pianod.startscript}

    if [ ! -f "$STARTSCRIPT" ]; then
      log_warning_msg "$STARTSCRIPT not found"
      log_end_msg 1
    else
      # Use params from config file if available or leave blank for defaults
      USERFILE=${USERFILE:-/etc/pianod.userfile}
      ARGS="-i $STARTSCRIPT ${PORT:+-p $PORT} ${USERFILE:+-u $USERFILE} ${LOGGING:+$LOGGING} $ARGS"

      start-stop-daemon --start --background --quiet --exec $DAEMON -- $ARGS
      exitval=$?

      # Because we are using --background flag to force pianod into the BG,
      # we can't get the actual return value from pianod, so 0 doesn't 
      # necessarily mean it actually started
      if [ $exitval = 0 ]; then
        # Check whether it started, but it might be too early...
        start-stop-daemon --status --exec $DAEMON
        exitval=$?
        
        # If hasn't started yet, wait a little while...
        if [ $exitval = 3 ]; then
          sleep 0.5
          start-stop-daemon --status --exec $DAEMON
          exitval=$?
        fi

        # Wait a little more...
        if [ $exitval = 3 ]; then
          sleep 0.5
          start-stop-daemon --status --exec $DAEMON
          exitval=$?
        fi

        # Wait a little more...
        if [ $exitval = 3 ]; then
          sleep 0.5
          start-stop-daemon --status --exec $DAEMON
          exitval=$?
        fi

        # Waited long enough; report success or failure
        log_end_msg $exitval
      else
        log_end_msg $exitval
      fi
    fi
    ;;

  stop)
    log_daemon_msg "Stopping pianod"
    start-stop-daemon --stop --quiet --exec $DAEMON
    log_end_msg $?
    ;;

  restart|reload|force-reload)
    $0 stop
    sleep 1
    $0 start
    ;;

  status)
    status_of_proc $DAEMON "pianod"
    ;;

  *)
    echo "Usage: /etc/init.d/pianod {start|stop|reload|restart|force-reload}"
    echo "Configuration loaded from $CONFIGFILE"
    exit 1
    ;;
esac

exit 0
