#! /bin/sh
#
# subsonic media streaming server
# Description:       Starts the Subsonic daemon. Subsonic is a web-based 
#                    music streamer, jukebox and Podcast receiver.
#                    See http://subsonic.org for more details.

# To change the startup parameters of Subsonic, modify 
# the SUBSONIC_ARGS variable below.
#
# Type "subsonic --help" on the command line to read an
# explanation of the different options.
#
# For example, to specify that Subsonic should use port 7070
# and use a Java memory heap size of 80 MB, use the following:
#
# SUBSONIC_ARGS="--port=7070 --max-memory=80"

SUBSONIC_ARGS=""

PIDFILE=/var/run/$NAME.pid

start() {
  if [ -e $PIDFILE ]; then
    ps -p $(cat $PIDFILE) > /dev/null
    if [ $? -eq 0 ]; then
      echo "Subsonic is already started"
      exit 1
    else
      rm -f $PIDFILE
    fi
  else
    /usr/bin/subsonic --pidfile=$PIDFILE $SUBSONIC_ARGS
  fi
}

stop() {
  if [ -e $PIDFILE ]; then
    ps -p $(cat $PIDFILE) > /dev/null
    if [ $? -eq 0 ]; then
      kill $(cat $PIDFILE)
      for i in $(seq 5); do
        ps -p $(cat $PIDFILE) > /dev/null
        if [ $? -eq 0 ]; then
          kill $(cat $PIDFILE)
          sleep 1
        else
          break
        fi
      done
      ps -p $(cat $PIDFILE) > /dev/null
      if [ $? -eq 0 ]; then
        kill -9 $(cat $PIDFILE)
      fi
      rm -f $PIDFILE
      echo "Subsonic stopped"
    else
      echo "Subsonic is not started"
      rm -f $PIDFILE
      exit 1
    fi
  else
    echo "Subsonic is not started"
    exit 1
  fi
}

status() {
  if [ -e $PIDFILE ]; then
    ps -p $(cat $PIDFILE) > /dev/null
    if [ $? -eq 0 ]; then
      echo "Subsonic is started"
    else
      echo "Subsonic is stopped"
      rm -f $PIDFILE
    fi
  else
    echo "Subsonic is stopped"
  fi
}

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

: