#!/usr/bin/env sh
#
# Simple wrapper to launch the python script.
#
# USAGE: Usage: launch.sh {start|stop|restart|status}
#
# TODO: use start-stop-daemon instead of _start (requierement #616 solves it)
#
# BUGS:
#   * script does not intercept return code of _start function
#     execution of "python ${DAEMON}…" may fails without warning (corrected
#     when #616 is closed)

DIR=$(dirname $0)
NAME=mpd_sima
DAEMON=${DIR}/src/mpd_sima

## Set these var to fit your preferences
PIDFILE="${DIR}/${NAME}.pid"
LOGFILE="${DIR}/${NAME}.log"
OPTIONS="--daemon"
##

_start ()
{    
        echo -n "Starting ${NAME}: "
        /usr/bin/env python "${DAEMON}" ${OPTIONS} \
                                        --pid="${PIDFILE}" \
                                        --log="${LOGFILE}"
}

_stop()
{
    echo -n "Stopping ${NAME}: "
    if !([ -w $PIDFILE ])
    then 
        echo "ERROR: Is ${NAME} running? PID file not found."
        ERR="1"
    else
        kill -15 $PID
        echo "done"
    fi
}

[ -e $PIDFILE ] && PID=$(cat "$PIDFILE")

case "$1" in
  start)
    if ( [ -w $PIDFILE ] && ps -p $PID 1> /dev/null )
    then
        echo "ERROR: ${NAME} already started ($NAME found running PID's $PID)"
        exit 1
    elif ( [ -w $PIDFILE ] )
    then
        echo "ERROR: PID file found while ${NAME} is not running (removing PID file)."
        rm $PIDFILE
        _start
        echo "done"
        exit 0
    fi
    _start
    echo "done"
    exit 0
    ;;
  stop)
    _stop
    exit ${ERR:-0}
    ;;
  restart)
    _stop
    sleep 1
    _start    
    echo "done"
  ;;
  status)
    if !([ -w $PIDFILE ])
    then
        echo "$NAME not running."
        exit 0
    fi
    echo "$NAME is running (pid: $PID)"
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|status}" >&2
    exit 1
    ;;
esac

exit 0

# Copyright (c) 2009, 2010, 2011 Jack Kaliko <efrim@azylum.org> {{{
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as
#  published by the Free Software Foundation; either version 3 of the
#  License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful, but
#  WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#  General Public License for more details.
#
#  You should have received a copy of the GNU General Public
#  License along with this program.
#  If not, see <http://www.gnu.org/licenses/>.
#
#  }}}

# vim:fileencoding=utf-8
