#!/bin/sh
### BEGIN INIT INFO
# Provides:          algo-uieng
# Required-Start:    $syslog algo-netman algo-watcher algo-main
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 6
# Short-Description: Provide user interface engine.
### END INIT INFO

# Copyright (C) 2012-2016 Algo Communication Products Ltd.

NAME=algo-uieng
PROG=/opt/algo/bin/algo-uieng
READCONF=/opt/algo/bin/readconf

PID_FILE=/var/run/algo-uieng.pid

get_ui_vol()
{
	VOL=$($READCONF audio.ui.vol)
	if [ $VOL = '0' ]; then
		VOL='0'
	elif [ $VOL = '1' ]; then
		VOL='54'
	elif [ $VOL = '2' ]; then
		VOL='63'
	elif [ $VOL = '3' ]; then
		VOL='76'
	elif [ $VOL = '4' ]; then
		VOL='90'
	elif [ $VOL = '5' ]; then
		VOL='107'
	elif [ $VOL = '6' ]; then
		VOL='127'
	elif [ $VOL = '7' ]; then
		VOL='152'
	elif [ $VOL = '8' ]; then
		VOL='180'
	elif [ $VOL = '9' ]; then
		VOL='214'
	elif [ $VOL = '10' ]; then
		VOL='255'
	else
		VOL='127'
		echo "UI volume not configured, using default" $VOL
	fi
}

start_app()
{
	/opt/algo/bin/bootui fillcolor all white
	/opt/algo/bin/bootui showtxt 22 "Starting user interface ..."

	CYTS_LINK=/usr/lib/arm-linux-gnueabi/ts0/cyts.so
	if [ ! -L $CYTS_LINK ]; then
		ln -sf /opt/algo/lib/cyts.so $CYTS_LINK
	fi
	export TSLIB_TSDEVICE=/dev/ttyS1
	export TSLIB_CONSOLEDEVICE=none
	export TSLIB_FBDEVICE=/dev/fb/0
	export QWS_MOUSE_PROTO=Tslib:/dev/ttyS1

	get_ui_vol

	# for some reason we have to play a wave file before set volume
	aplay -D ui /opt/algo/sounds/silence.wav
	amixer set uivol $VOL

	CMD="start-stop-daemon --start --background --make-pidfile \
		--pidfile $PID_FILE --exec /opt/algo/bin/algo-uieng"

	VNC_USE=$($READCONF ui.vnc.use -c /apps/curapp/user/ui.conf)
	if [ "$VNC_USE" = "1" ]; then
		CMD=$CMD" -- -display 'Multi: LinuxFb VNC::size=640x480:depth=16:0'"
	fi

	eval $CMD
}

stop_app()
{
	start-stop-daemon --stop --retry 5 --pidfile $PID_FILE
}

case "$1" in
start)
	start_app
	;;

stop)
	/opt/algo/bin/cmdmsg /WatcherCmdQ "service dereg algo-uieng"
	stop_app
	;;

restart)
	stop_app
	start_app
	;;

*)
	echo "Usage: /etc/init.d/algo-uieng {start|stop|restart}" >&2
	exit 1
	;;
esac

exit 0
