#!/bin/sh

lcd4linux=$(which lcd4linux || type -p lcd4linux)

[ -n $lcd4linux ] || exit 1

. /etc/init.d/functions
. /etc/init.d/globals

lcd4linux_conf() {
	if [ ! -e /tmp/lcd/layout ]; then
		mkdir -p /tmp/lcd
		echo Pearl_standard > /tmp/lcd/layout
	fi
	read layout < /tmp/lcd/layout
	test ${layout##*_} = user && CONF_DIR=/var/etc || CONF_DIR=/etc

	chmod 600 ${CONF_DIR}/lcd4linux.conf
	chown 0:0 ${CONF_DIR}/lcd4linux.conf

	printf "${CONF_DIR}/lcd4linux.conf"
}
lcd4linux_pid=/var/run/lcd4linux.pid

lcd4image_conf=/tmp/lcd4image.conf
lcd4image_pid=/var/run/lcd4image.pid
lcd4linux_png=/tmp/lcd4linux.png

doStart() {
	( # do always run in background
		# /tmp/.lcd4linux gets created by neutrino when lcd4l-Thread is ready
		while [ ! -e /tmp/.lcd4linux ]; do
			sleep 1;
		done

		lcd4linux_conf=$(lcd4linux_conf)

		# /tmp/.lcd-* gets created by extdisplay script when a display was found
		if [ -e /tmp/.lcd-* ]; then
			$lcd4linux -f $lcd4linux_conf -p $lcd4linux_pid
		fi

		if [ "$(get_setting lcd4l_screenshots)" == "1" ]; then
			cp $lcd4linux_conf $lcd4image_conf
			sed -i "s|^	driver.*|	driver	'Image'\n	format	'PNG'\n	pixel	'1+0'\n	gap	'0x0'|g" $lcd4image_conf

			$lcd4linux -f $lcd4image_conf -p $lcd4image_pid -o $lcd4linux_png
		fi
	) &
}

doStop() {
	for PIDFILE in $lcd4image_pid $lcd4linux_pid; do
	if [ -e $PIDFILE ]; then
		# read pid from pidfile
		read PID < $PIDFILE

		# kill child processes
		CHILDS=$(ps -o pid --ppid $PID --no-heading)
		for CHILD in $CHILDS; do
			kill -KILL $CHILD
		done

		# terminate main process
		kill -TERM $PID
		sleep 2
	fi
	done
	rm -f $lcd4image_conf $lcd4linux_png
}

doOff() {
	# /tmp/.lcd-* gets created by extdisplay script when a display was found
	if [ -e /tmp/.lcd-* ]; then
		echo "LCD::backlight(0)" | $lcd4linux -i > /dev/null 2>&1
	fi
}

case "$1" in
	start)
		doStart
	;;
	stop)
		doStop
	;;
	off)
		doStop
		doOff
	;;
	restart|reload)
		doStop
		doStart
	;;
	*)
		echo "[${BASENAME}] Usage: $0 {start|stop|off|restart|reload}"
	;;
esac
