#!/bin/bash

### BEGIN INIT INFO
# Provides:        wdmcserver
# Required-Start:  $network  $syslog
# Required-Stop:   $network  $syslog
# Default-Start:   2 3 4 5
# Default-Stop:    0 1 6
# Short-Description: Start wdmcserver daemon
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:/usr/local/sbin
DISPATCHER_PIPE=/tmp/WDMCDispatcher.pipe
WDMC_NOTIFICATION_SOCKET=/tmp/WDMCNotification.socket
INSTALL_DIR=/usr/local/wdmcserver
export LC_ALL=en_US.UTF-8

. /lib/lsb/init-functions

export LD_LIBRARY_PATH=$INSTALL_DIR/lib:$INSTALL_DIR/bin
DAEMON=$INSTALL_DIR/bin/wdmcserver
PIDFILE=/var/run/wdmcserver.pid

ORION_DB=/usr/local/nas/orion/orion.db
ADDVOLUMES=$INSTALL_DIR/bin/AddVolumes.py
RMVOLUMESDB=$INSTALL_DIR/bin/RmVolumesDB.py
TMP_VOLUMES=/tmp/Volumes.xml
GET_BATTERY_STATUS=/usr/local/sbin/power_get_battery_status.sh
GET_EXTERNAL_SCAN=/usr/local/sbin/getExternalStorageScan.sh
export WD_HDD="/shares/.USB"

test -x $DAEMON || exit 5

# Use this function to launch the daemon w/ "share" group ownership
launch_as_newgrp() {

newgrp share <<FOO
umask 0
cd $INSTALL_DIR/bin
start-stop-daemon --start --quiet --oknodo -b -m --pidfile $PIDFILE --exec $DAEMON -- $VOLUMES_FILE $POWERMODE $EXTERNALSCAN  2> /dev/null
FOO

}

case $1 in
	start)
		log_daemon_msg "Starting wdmcserver" "wdmcserver"
		renice 0 -p $$
		mkfifo $DISPATCHER_PIPE
		chmod 777 $DISPATCHER_PIPE
		ulimit -s 256
		export WDMC_CHILD_MEMSW_LIMIT=314572800

		if [ -f $TMP_VOLUMES ]; then
			rm -f $TMP_VOLUMES
		fi
		if [ -f $GET_BATTERY_STATUS ]; then
			$GET_BATTERY_STATUS | grep -w discharging > /dev/null
			if [ $? -eq 0 ]; then
				POWERMODE="-b on"
			else
				POWERMODE=
			fi
		else
			POWERMODE=
		fi

		if [ -f $GET_EXTERNAL_SCAN ]; then
			$GET_EXTERNAL_SCAN | grep 0 > /dev/null
			if [ $? -eq 0 ]; then
				EXTERNALSCAN="-x off"
			else
				EXTERNALSCAN="-x on"
			fi
		else
			EXTERNALSCAN="-x off"
		fi

		export MAGICK_CONFIGURE_PATH=$INSTALL_DIR/lib/ImageMagick-6.7.9/config
		export MAGICK_TMPDIR=/shares/Public/.wdmc
		launch_as_newgrp
		status=$?
		log_end_msg $status
		# Now wait for the socket to be ready
		while [ ! -S $WDMC_NOTIFICATION_SOCKET ]; do
			sleep 1
		done
		if [ -f $ORION_DB ] && [ -f $ADDVOLUMES ]; then
			python $ADDVOLUMES
		fi
		;;
	stop)
		log_daemon_msg "Stopping wdmcserver" "wdmcserver"
		# Try several times to stop wdmcserver process, last try is to send KILL signal
		start-stop-daemon --stop --oknodo --signal INT --quiet --pidfile $PIDFILE --retry INT/5/INT/5/INT/5/KILL/5  2> /dev/null
		status=$?
		# Wait a little
		sleep 1
		# Although wdmc_pid is not used, still assign pid to wdmc_pid in case want
		# to debug later and dump the pid value
		wdmc_pid=`pidof wdmcserver`
		getpid_status=$?
		# In the following abnormal cases, start-stop-daemon return status is 0 and process is not terminated:
		# - pid file does NOT match process id
		# - pid file does NOT exist
		if [ $status -ne 0 ] || [ $getpid_status -eq 0 ]; then
			 # If somehow reach this, then just kill the process
			 # but don't use PIDFILE as that may be inaccurate
			 kill -9 `pidof wdmcserver`
			 status=$?
			 if [ $status -ne 0 ]; then
				 log_end_msg 1
				 exit $status
			 fi
		fi
		# remove stale PID file
		if [ -f $PIDFILE ]; then
			# Stale PID file (wdmcserverd was succesfully stopped)
			rm -f $PIDFILE
		fi
		log_end_msg 0
		rm -f $WDMC_NOTIFICATION_SOCKET
		;;
	reset)
		$0 stop
		log_daemon_msg "Removing databases" "wdmcserver"
		if [ -f $ORION_DB ] && [ -f $RMVOLUMESDB ]; then
			python $RMVOLUMESDB
		fi
		$0 start
		;;
	restart)
		$0 stop && sleep 5 && $0 start
		;;
	try-restart)
		if $0 status >/dev/null; then
			$0 restart
		else
			exit 0
		fi
		;;
	status)
		pidofproc -p $PIDFILE $DAEMON >/dev/null
		status=$?
		if [ $status -eq 0 ]; then
			log_success_msg "wdmcserver is running."
		else
			log_failure_msg "wdmcserver is not running."
		fi
		exit $status
		;;
	info)
		cd $INSTALL_DIR/bin
		$DAEMON -i
		exit 0
		;;
	*)
		echo "Usage: $0 {start|stop|restart|reset|try-restart|status|info}"
		exit 2
		;;
esac
