#!/bin/bash
#
#	/etc/rc.d/init.d/bubbleserver
#
# Starts the BubbleUPnPServer daemon
#
# chkconfig: 345 20 80
# description: BubbleUPnPServer
# processname: java BubbleUPnPServer.jar

### BEGIN INIT INFO
# Provides: BubbleUPnPServer
# Required-Start: $network
# Required-Stop: $null
# Default-Start: 3 5
# Default-Stop: 0 1 2 6
# Description: BubbleUPnPServer
# Short-Description: BubbleUPnPServer
### END INIT INFO

#. /etc/rc.d/init.d/functions

# Source function library
if [ -f /lib/lsb/init-functions ]; then
   . /lib/lsb/init-functions
   rc_reset
elif [ -f /etc/rc.d/init.d/functions ]; then
   . /etc/rc.d/init.d/functions
fi


NAME=bubbleserver
DESC="Bubble Server Upnp Proxy"

if [ `id -u` -ne 0 ]; then
   echo "You need root privileges to run this script"
   exit 1
fi


# Define other required variables
PID_FILE=/var/run/$NAME.pid
USER=bubbleserver

DAEMON_PATH="/opt/bubbleserver"

DAEMON="java -Xss256k -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -jar BubbleUPnPServerLauncher.jar"
DAEMON_OPTS=""

#
# Function that starts the daemon/service
#
do_start()
{

  if [ -z "$DAEMON" ]; then
    echo "not found - $DAEMON"
    exit 1
  fi

  if pidofproc -p "$PID_FILE" $0 >/dev/null; then
    exit 0
  fi
  
  # to make sure ffmpeg is found and used if present in start directory
  export PATH=.:${PATH}

  cd $DAEMON_PATH
  echo -n "Starting $DESC: "
  runuser -s /bin/sh -c "exec $DAEMON $DAEMON_OPTS" ${USER} &

  RETVAL=$?
  local PID=$!
  # runuser forks rather than execing our process.
  usleep 500000
  JAVA_PID=$(ps axo ppid,pid | awk -v "ppid=$PID" '$1==ppid {print $2}')
  PID=${JAVA_PID:-$PID}
  echo $PID > $PID_FILE
  [ "$PID" = "$JAVA_PID" ] && log_success_msg
}

#
# Function that stops the daemon/service
#
do_stop()
{
  echo -n "Stopping $DESC: "
  if [ -f $PID_FILE ]; then
    PID=`cat $PID_FILE`
    kill -HUP $PID
    RETVAL=$?
    [ $RETVAL = 0 ] && rm -f ${PID_FILE} && log_success_msg $"Ok"
  else
      log_failure_msg $"pidfile not found"
  fi
  echo
}

check_status ()
{
        if [ -f /etc/SuSE-release ]; then 
           /sbin/checkproc -p $PID_FILE $0
           rc_status -v
        else
           status $NAME
           RETVAL=$?
        fi
}

case "$1" in
  start)
    do_start
    ;;
  stop)
    do_stop
    ;;
  restart|reload)
    do_stop
    do_start
    ;;
  status)
    echo -n "$DESC"
    check_status
    exit $?
    ;;
  *)
    echo "Usage: $SCRIPTNAME {start|stop|status|restart}" >&2
    exit 3
    ;;
esac

echo
exit 0
