#! /bin/sh

HMI_PROGRAM=${HMI_PROGRAM:-/usr/bin/embedded-hmi}
HMI_LOG_FILE=${HMI_LOG_FILE:-/var/log/embedded-hmi.log}

# Start the DHCP server if needed
if grep -i 'Dhcp_server[[:blank:]]*=[[:blank:]]1' /data/config/devices.config >/dev/null 2>&1
then
	/usr/sbin/udhcpd /etc/udhcpd.conf &
fi


# Uncomment the next line to show the mouse pointer.
# export VISIBLE_MOUSE=1

export QT_QPA_FONTDIR=/usr/share/fonts/truetype/
export DISPLAY=:0.0

/usr/bin/Xorg ${DISPLAY} -br -pn &

/usr/bin/no-screen-saver &

if ! [ -f "/data/custom/help-en.html" ] || [ "/data/custom/help-en.html" -ot "/usr/share/embedded-hmi/help-en.html" ]
then
	mkdir -p /data/custom/
	cp /usr/share/embedded-hmi/* /data/custom/
fi

${HMI_PROGRAM} ${HMI_ARGS} > "${HMI_LOG_FILE}" 2>&1 &

# Not-so-elegant hack to avoid touchscreen driver crash.
if lsmod | grep edt_ft5x06 > /dev/null 2>&1
then
	counter=0
	while true
	do
		sleep 1
		if grep 'bug' /var/log/Xorg.0.0.log >/dev/null 2>&1
		then
			> /var/log/Xorg.0.0.log
			rmmod edt_ft5x06
			modprobe edt_ft5x06
			continue
		fi
		counter=$(($counter + 1))
		if [ "$counter" = "60" ]
		then
			counter=0
			rmmod edt_ft5x06
			modprobe edt_ft5x06
		fi
	done
fi

exit 0

