#!/bin/sh
# flexa-app start-up script.

APP_DIR="/mnt/data/package"
if [ -f ${APP_DIR}/run.py ]; then
	APP_NAME="run.py"
elif [ -f ${APP_DIR}/default.lua ]; then
	APP_NAME="default.lua"
elif [ -f ${APP_DIR}/install.json} ]; then
 	APP_NAME=$( jq -r '.scriptPath' ${APP_DIR}/install.json )
else 
	exit 100
fi

APP_BIN=${APP_DIR}/${APP_NAME}
APP_PID_FILE="/var/run/${APP_NAME}.pid"
CFG_NAME="flexa"

# In case of lua executable add package folder to default LUA search path,
# otherwise the interpreter will not be able to find any lua modules
# provided with the package
echo "$APP_BIN" |  grep -i '.*\.lua' && export LUA_PATH="${APP_DIR}/?.lua;;" || export LUA_PATH=""
LUA_CPATH="/usr/lib/lua/5.1/?.so"
export LUA_CPATH

WD_NAME="barix_watchdog"
WD_BIN="/usr/bin/${WD_NAME}"

sound_wait_sonic_ip() {
        local c=0

        echo "sound: Waiting Sonic IP to end..."
        while [ ${c} -le 32 ]; do
                if [ `/bin/pidof mpg123` ]
                then
                        sleep 1
                        echo "sound: Waiting Sonic IP to end..."
                else
                        echo "sound: Waiting Sonic IP to end...OK."
                        return 0
                fi
                ((c++))
        done
        echo "sound: Waiting Sonic IP to end...TIMEOUT"
        return 1
}

configure_audio() {
	# checks amplifier/mic/line-in settings, and
	# sets the controls accordingly
	# checking for correct limits
	if [ "$AUDIO_VOLUME" == "" -o "$AUDIO_VOLUME" -gt 100 -o "$AUDIO_VOLUME" -lt 0 ]; then
			echo "Volume value is out of range, using default value of 50% !"
			AUDIO_VOLUME=50
	fi

	# set the preconfigured values and ALSA mixer switches for mic/line-in
	if [ "$AUDIO_AMPLIFIER" == "on" ] ; then
			echo "AUDIO: Switching ON the amplifier ..."
			echo "1" > /sys/class/gpio/gpio17/value
	else
			echo "AUDIO: Switching OFF the amplifier ..."
			echo "0" > /sys/class/gpio/gpio17/value
	fi


	if [ "$AUDIO_MIC_LINEIN" == "mic" ] ; then
			echo "AUDIO: Mic ON, Line-in OFF"
			#echo none > /sys/class/leds/ann60\:mic/trigger
			# Configure the ALSA mixer switches for mic
			echo "AUDIO: Muting the Line-in ..."
			AUDIO_MIC_BOOST="on"
			#AUDIO_AD_GAIN=0

			#unmute and enable capture
			amixer sset "Line In" mute nocap
			amixer sset "Mic1" mute cap
	else
			echo "AUDIO: Mic OFF, Line-in ON"
			#echo default-on > /sys/class/leds/ann60\:mic/trigger
			echo "AUDIO: Muting the microphone ..."
			AUDIO_MIC_BOOST="off"
			#AUDIO_MIC_GAIN=0
			#/usr/bin/amixer -q -- sset 'Capture PGA' "$AUDIO_AD_GAIN"
			amixer sset "Mic1" mute nocap
			amixer sset "Line In" mute cap
	fi


	# Finally set the audio parameters via amixer
	# Volume
	/usr/bin/amixer -q -- sset 'ADC Gain' "$AUDIO_AD_GAIN"
	/usr/bin/amixer -M -q sset 'DAC' "$AUDIO_VOLUME%"

	#Mic/Line In gain
	if [ "$AUDIO_MIC_BOOST" == "on" ] ; then
			/usr/bin/amixer -q -- sset 'Mic1 Boost' "$AUDIO_MIC_GAIN"
	else
			/usr/bin/amixer -q sset 'Mic1 Boost' "0%"
	fi
	
}


check_wd() {
    # Argument $1 is a process full command line regular expression to be used
    # with pgrep/pkill.
	proc_re=$1
    # Argument $2 is the timeout in seconds to wait for a process still running
    # before killing it.
	timeout=$2
    # Argument $3 when set, if this function endded up force killing the
    # process, it will also kill all child processes.
	kill_children=$3

	# Loop waiting for process to exit, with timeout.
	ended=0
	count=1
	echo "Waiting for '${proc_re}' to end..."
	while [ ${count} -le ${timeout} ]; do
		if pgrep -f "${proc_re}" > /dev/null; then
			echo "Still running..."
			sleep 1
		else
			echo "Waiting for '${proc_re}' to end...DONE"
			ended=1
			break
		fi
		((count++))
	done

	# Force process killing if waiting timed out.
	if [ ${ended} -ne 1 ]; then
		children=$(pgrep -P $(pgrep -f ${APP_BIN}))
		echo "Children ${children}"
		echo "Waiting for '${proc_re}' to end...FAILED => Kill it!"
		pkill -9 -f "${proc_re}"
		rc=$?
		echo "Killed '${proc_re}' (rc=${rc})"
		if [ ! -z ${kill_children} ] && [ ! -z ${children} ]; then
			for child in "${children}"; do
				kill -9 ${child}
				echo "Killed child ${child}"
			done
		fi
	fi
}

start_wd() {
	echo "Starting '${APP_NAME}' via '${WD_NAME}'..."
	start-stop-daemon -S -b -o -x ${WD_BIN} -p ${APP_PID_FILE} -m -- \
		${APP_BIN} ${APP_OPTS}
	rc=$?
	if [ ${rc} -ne 0 ]; then
		echo "Starting '${APP_NAME}' via '${WD_NAME}'...FAILED (rc=${rc})"
		# Should not have been created, but just in case.
		rm -f ${APP_PID_FILE}
		exit ${rc}
	fi
	echo "Starting '${APP_NAME}' via '${WD_NAME}'...OK"
}

stop_wd() {
	echo "Stopping '${APP_NAME}' via '${WD_NAME}'..."
	# Give a chance for the wd/app to stop cleanly with SIGINT.
	start-stop-daemon -K -s 2 -o -p ${APP_PID_FILE}
	rc=$?
	echo "Stopping '${APP_NAME}' via '${WD_NAME}'...DONE (rc=${rc})"
	# Make sure the wd/app are stopped, forcing if necessary.
	check_wd "${WD_BIN} ${APP_BIN}" 5
	check_wd "${APP_BIN}" 5 1
	# Drop the PID file.
	rm -f ${APP_PID_FILE}
}



start() {
	# Configure.
	#configure_audio	
	
	# Just defer to start_wd().
	sound_wait_sonic_ip
	echo "${APP_NAME}: Starting the ${APP_NAME} application..."
	start_wd
	
	echo "${APP_NAME}: Starting the ${APP_NAME} application...DONE"
}

stop() {
	# Just defer to stop_wd().
	echo "${APP_NAME}: Stopping the ${APP_NAME} application..."
	stop_wd
	echo "${APP_NAME}: Stopping the ${APP_NAME} application...DONE"
}

restart() {
	stop
	start
}


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

exit 0

