#!/bin/sh
##########################################
# BubbleUPnP Server Synology package     #
# created by winxi, inspired by patters  #
# see http://pcloadletter.co.uk/         #
##########################################

BUBBLE_USER="bubbleupnp"
BUBBLE_HOME="$(cat /etc/passwd | grep "${SYNOPKG_PKGNAME} daemon user" | cut -f6 -d':')"
APP_DATA="appData"
PID_FILE="/var/run/bubbleupnpserver.pid"

bubbleupnp_java_status ()
{
	# when PID_FILE does not exist, it must be assumed that BubbleUPnP Server is not running
	[ ! -e "$PID_FILE" ] && return 3
	PID=$(cat "$PID_FILE")
	# when PID_FILE is empty, it must be assumed that BubbleUPnP Server is not running
	[ -z "$PID" ] && return 1
	# check whether a process with the PID from PID_FILE is run by the daemon user
	ps | grep "$PID" | grep "${BUBBLE_USER:0:8}" > /dev/null
}

clean_up ()
{
	# remove PID_FILE
	[ -e "$PID_FILE" ] && rm "$PID_FILE"
}

case $1 in
	start)
		source /etc/profile
		# check for a proper Java installation, a DSM update may have reset /etc/profile to defaults
		if [ -z "$JAVA_HOME" ]; then
			# search for the missing Java path
			counter=1
			while [ -d "/volume${counter}" ] ;
			do
				JAVA_HOME="/volume${counter}/@appstore/java6/jre"
				if [ -d "$JAVA_HOME" ]; then break
				fi
				JAVA_HOME="/volume${counter}/@appstore/java7/jre"
				if [ -d "$JAVA_HOME" ]; then break
				fi
				JAVA_HOME="/volume${counter}/@appstore/java8/jre"
				if [ -d "$JAVA_HOME" ]; then break
				fi

				let counter=counter+1
				JAVA_HOME=""
			done
		fi
		if [ -z "$JAVA_HOME" -o ! -f "$JAVA_HOME/bin/java" ]; then
			# Java installation couldn't be found
			echo "The Java installation seems to be corrupted. \
			Please reinstall the Java Synology package." >> $SYNOPKG_TEMP_LOGFILE
			exit 1
		fi

		#set the current timezone for Java so that log timestamps are accurate
	    #we need to use the modern timezone names so that Java can figure out DST
	    SYNO_TZ=$(cat /etc/synoinfo.conf | grep timezone | cut -f2 -d'"')
	    SYNO_TZ=$(grep "^${SYNO_TZ}" /usr/share/zoneinfo/Timezone/tzname | sed -e "s/^.*= //")
	    grep "^export TZ" ${BUBBLE_HOME}/.profile > /dev/null \
	    && sed -i "s%^export TZ=.*$%export TZ='${SYNO_TZ}'%" ${BUBBLE_HOME}/.profile \
		|| echo export TZ=\'${SYNO_TZ}\' >> ${BUBBLE_HOME}/.profile

		# start BubbleUPnP Server
        if bubbleupnp_java_status; then
			echo "BubbleUPnP Server is already running." >> $SYNOPKG_TEMP_LOGFILE
			exit 1
		else
			# pass parameters to bubble.sh
			sh "${SYNOPKG_PKGDEST}"/bubble.sh "$PID_FILE" "$APP_DATA" "$SYNOPKG_PKGDEST" "$BUBBLE_HOME" "$BUBBLE_USER" "$JAVA_HOME"
		fi
		exit 0
	;;

	stop)
		if bubbleupnp_java_status; then
			# kill BubbleUPnP Server
			PID=$(cat "$PID_FILE")
			kill $PID

			# check for a successful kill
			kill_time=1
			while bubbleupnp_java_status && [ "$kill_time" -le 20 ]
			do
				sleep 1
				let kill_time=kill_time+1
			done

			# if graceful kill wasn't successful, force kill
			if bubbleupnp_java_status; then
				kill -9 $PID
				# DSM notification about forced kill
				synodsmnotify @administrators "BubbleUPnP Server" "BubbleUPnP Server had to be stopped using a forced kill."
			fi

			# the BubbleUPnP Server Java process has been killed, so clean up now
			clean_up
			exit 0
		else
			echo "BubbleUPnP Server is not running." >> $SYNOPKG_TEMP_LOGFILE
			# the BubbleUPnP Server Java process may have been killed from outside the package center, so clean up
			clean_up
			exit 1
		fi
	;;

	status)
		if bubbleupnp_java_status; then
			exit 0
		else
			# the BubbleUPnP Java process may have been killed from outside the package center, so clean up
			clean_up
			exit 3
		fi
	;;

	log)
		# extract the log of the running session out of the rotated logfiles and
		# write it to ${APP_DATA}/synoCurrent.log
		LASTSTART0=$(grep -n "starting BubbleUPnP Server" \
		"${BUBBLE_HOME}/${APP_DATA}/BubbleUPnPServer.log.0" | cut -d: -f1 | tail -n 1)
		if [ -n "${LASTSTART0}" ]; then
			tail "${BUBBLE_HOME}/${APP_DATA}/BubbleUPnPServer.log.0" -n +${LASTSTART0} \
			> "${BUBBLE_HOME}/${APP_DATA}/synoCurrent.log"
		else
			LASTSTART1=$(grep -n "starting BubbleUPnP Server" \
			"${BUBBLE_HOME}/${APP_DATA}/BubbleUPnPServer.log.1" | cut -d: -f1 | tail -n 1)
			if [ -n "${LASTSTART1}" ]; then
				tail "${BUBBLE_HOME}/${APP_DATA}/BubbleUPnPServer.log.1" -n +${LASTSTART1} \
				> "${BUBBLE_HOME}/${APP_DATA}/synoCurrent.log"
				cat "${BUBBLE_HOME}/${APP_DATA}/BubbleUPnPServer.log.0" \
				>> "${BUBBLE_HOME}/${APP_DATA}/synoCurrent.log"
			else
				# if in both files no start is detected, server seems to be spamming
				# or to be up long. Just show BubbleUPnPServer.log.0
				echo "${BUBBLE_HOME}/${APP_DATA}/BubbleUPnPServer.log.0"
				exit 0
			fi
		fi
		echo "${BUBBLE_HOME}/${APP_DATA}/synoCurrent.log"
		exit 0
	;;
esac
