#!/bin/sh

# Read our configuration file and set variables
APPNAME="ewft.minidlna"
DISPLAYNAME="MiniDLNA"
PLGCONFFILE="/boot/config/plugins/ewft.minidlna/${APPNAME}.cfg"
APPCONFFILE="settings.json"
APPEXECUTABLE="/usr/sbin/minidlnad"
PIDFILE="/var/run/minidlna/minidlna.pid"
PLGLOGFILE="/var/log/minidlna/${APPNAME}.log"
ARRAYSTATE=`grep fsState /var/local/emhttp/var.ini | sed -n 's!fsState="\(.*\)"!\1!p'`
source "$PLGCONFFILE"

# This needs to be near the top so the dependency common directory can be set
app_check_cache() {
	local COMMONVAR="false"
	if [ -e "/mnt/cache" ] && [ -w "/mnt/cache" ]; then
		local CDRIVE=$( stat -f -c '%T' "/mnt/cache" )
		if [ "$CDRIVE" != "ramfs" ] && [ "$CDRIVE" != "tmpfs" ] && [ "$CDRIVE" != "proc" ] && [ "$CDRIVE" != "sysfs" ] && [ "$CDRIVE" != "msdos" ]; then
			COMMONVAR="true"
		fi
	fi

	echo "$COMMONVAR"
}

# Check for cache drive and make sure its an actual disk drive
PHAZECOMMON="/usr/local/PhAzE-Common"
COMMONCHECK=`app_check_cache`
[ "$COMMONCHECK" == "true" ] && PHAZECOMMON="/mnt/cache/.PhAzE-Common"
STARTFILE="$PHAZECOMMON/${APPNAME}/startcfg.sh"

app_start() {
	# Get array status and exit if not started
	if [ "$ARRAYSTATE" != "Started" ]; then
		app_logger "Starting $DISPLAYNAME..." info all
		app_logger "Start failed: Array stopped " warn all
		return
	fi

	# Set service to enabled
	[ "$SERVICE" != "enable" ] && sed -i 's/disable/enable/' "$PLGCONFFILE"

	# No-op if already running and install if not installed
	local STATUS=`app_status`
	if [ "$STATUS" == "RUNNING" ]; then
		app_logger "Starting $DISPLAYNAME..." info all
		app_logger "Start OK: Already running " info all
		return
	else
		app_logger "Starting $DISPLAYNAME..." info all

		# Create export file and check dependencies
		# write_export_config
		if [ "$EXPORTOK" == "no" ]; then
			app_logger "Start failed: Unable to update export file " error all
			return
		fi
	fi

	# Make working directories and write the app config file
	#app_make_dirs
	#write_app_config

	
	# Start the app
	sudo -H -u root /bin/bash -c 'nohup '$APPEXECUTABLE' > /dev/null 2>&1 &'

	# Checks if the app started properly or not, giving it 10 seconds to create the PID file
	local TIMER=0
	while [ ! -e "$PIDFILE" ]; do
		let TIMER=$TIMER+1
		sleep 1
		if [ $TIMER -gt 10 ]; then
			app_logger "Start failed: No PID created " error all
			sleep 3
			return
		fi
	done

	# Check if process specified in the PID is actually running, as a double check
	TIMER=0
	while [[ -e "$PIDFILE" && ! -f /proc/`cat "$PIDFILE" 2> /dev/null`/exe ]]; do
		let TIMER=$TIMER+1
		sleep 1
		if [ $TIMER -gt 5 ]; then
			app_logger "Start failed: PID created but no process exists " error all
			sleep 3
			return
		fi
	done

	# Notify if start was successful or failed
	app_logger "Start OK! " info all
	sleep 1
}

app_stop() {
	# No-op if already running
	local STATUS=`app_status`
	app_logger "Stopping $DISPLAYNAME..." info all
	if [ "$STATUS" == "STOPPED" ]; then
		app_logger "Stop OK: Already stopped " info all
		sleep 1
		return
	fi

	# Send the kill command to gracefully shutdown
	kill $(cat "$PIDFILE" ) 2> /dev/null

	# Begin a timer for shutdown, force kill process if not shut down by end of timer
	let TIMER=0
	while [ -e "$PIDFILE" ]; do
		let TIMER=$TIMER+1
		sleep 1

		# Process has ended but PID file remains, so remove it
		if [ ! -f /proc/`cat "$PIDFILE" 2> /dev/null`/exe ]; then
			rm "$PIDFILE" 2> /dev/null
		fi

		if [ $TIMER -gt 30 ]; then
			app_logger "Taking too long: Force killing process" warn log
			kill -9 $(cat "$PIDFILE" ) 2> /dev/null
			rm "$PIDFILE"
			break
		fi
	done

	app_logger "Stop OK! " info all
	sleep 1
}

app_restart() {
	app_stop
	app_start
}

app_status() {
	# Get running status
	local STATUS=""
	if [ ! -f "$APPEXECUTABLE" ]; then
		STATUS="NOT INSTALLED"
	elif [ -f "$PIDFILE" ] && [ -f /proc/`cat "$PIDFILE" 2> /dev/null`/exe ]; then
		STATUS="RUNNING"
	else
		STATUS="STOPPED"

		# Remove stale PID file that shouldn't exist anymore
		[ -f "$PIDFILE" ] && rm -f "$PIDFILE"
	fi

	echo "$STATUS"
}

app_buttonstart() {
	if [ -f "$PLGCONFFILE" ]; then
		sync_app_config
		app_start
	else
		app_logger "Start failed: Config file missing - Reinstall plugin " error all
		sleep 3
	fi
}




app_logger() {
	# First passed item is the text ($1), secone item is severity ($2 - info, warn, error), third is where to log ($3 - all, log)
	local LOGTEXT=$1
	local LOGTYPE=$2
	local LOGVAR=$3
	local TIMESTAMP=`date +"%Y-%m-%d %T"`

	# Set the type of log
	if [ "$LOGTYPE" == "info" ]; then
		TYPE="[INFO]"
	elif [ "$LOGTYPE" == "warn" ]; then
		TYPE="[WARNING]"
	elif [ "$LOGTYPE" == "error" ]; then
		TYPE="[ERROR]"
	fi

	# If log file doesn't exist, make it
	if [ ! -f "$PLGLOGFILE" ]; then
		mkdir -p "/var/log/minidlna"
		touch "$PLGLOGFILE"
	fi

	# Echo the text to display and log, or just log file
	if [ "$LOGVAR" == "all" ]; then
		echo -e "${LOGTEXT}"
		echo -e "${TIMESTAMP} ${TYPE}\t${LOGTEXT}" >> "$PLGLOGFILE"
	elif [ "$LOGVAR" == "log" ]; then
		echo -e "${TIMESTAMP} ${TYPE}\t${LOGTEXT}" >> "$PLGLOGFILE"
	fi
}

app_enable() {
	app_stop
	SERVICE=enable
	app_start
}

app_disable() {
	app_stop
	SERVICE=disable
}

app_curver() {
	# This gets the current version installed
	local CURVER=""
	if [ "$ARRAYSTATE" == "Started" ]; then
		[ -e "$APPEXECUTABLE" ] && CURVER=`sudo -H -u root /bin/bash -c ''$APPEXECUTABLE' -V 2>&1' | cut -f1 | awk '{print $2}'` || CURVER="NOT INSTALLED"
	fi

	echo "$CURVER"
}

case "$1" in
	'start')
		app_logger "*** Start Initiated ***" info log
		[ "$2" == "force" ] && ARRAYSTATE="Started"
		app_start
	;;
	'stop')
		app_logger "*** Stop Initiated ***" info log
		app_stop
	;;
	'restart')
		app_logger "*** Restart Initiated ***" info log
		app_restart
	;;
	'status')
		app_status
	;;
	'currentversion')
		app_curver
	;;
	'enable')
		app_logger "*** Apply - Enable Initiated ***" info log
		VAR="$2"
		VAR=`echo "$VAR" | sed 's!@20! !g'`
		VAR=`echo "$VAR" | sed 's!@@2200!@20!g'`
		VARS=( $VAR )
		app_enable ${VARS[0]} ${VARS[1]} ${VARS[2]} ${VARS[3]} ${VARS[4]} ${VARS[5]} ${VARS[6]} ${VARS[7]} ${VARS[8]} ${VARS[9]} ${VARS[10]} ${VARS[11]} ${VARS[12]} ${VARS[13]}
	;;
	'disable')
		app_logger "*** Apply - Disable Initiated ***" info log
		VAR="$2"
		VAR=`echo "$VAR" | sed 's!@20! !g'`
		VAR=`echo "$VAR" | sed 's!@@2200!@20!g'`
		VARS=( $VAR )
		app_disable ${VARS[0]} ${VARS[1]} ${VARS[2]} ${VARS[3]} ${VARS[4]} ${VARS[5]} ${VARS[6]} ${VARS[7]} ${VARS[8]} ${VARS[9]} ${VARS[10]} ${VARS[11]} ${VARS[12]} ${VARS[13]}
	;;
	*)
	echo "usage $0 [start | stop | restart | status | install | update | updateplg | downgradeplg | removeplg | latestversion | currentversion]"
esac
