#!/bin/bash
cmd_string=(${0//// })
cmd=${cmd_string[${#cmd_string[*]} - 1]}
temp_path="/run"

# Verify that we are running single copy
tmp_ifs="$IFS"
IFS=$'\n'

ps_list=(`ps -C ${cmd} -o args --no-header`)
[ "${#ps_list[*]}" -gt 1 ] && exit 0

IFS="$tmp_ifs"

# supported_resolution_list=(`/usr/sbin/modetest -M tilcdc -c | sed -ne "s/^[[:space:]]*\([[:digit:]]\+x[[:digit:]]\+\)[[:space:]]\+\([[:digit:]]\+\).*driver$/\1@\2/p" | sort -nr`)
# Not confident in above change
supported_resolution_list=(`/usr/sbin/modetest -M tilcdc -c | sed -ne "s/^[[:space:]]*\([[:digit:]]\+x[[:digit:]]\+\)[[:space:]]\+\([[:digit:]]\+\).*driver$/\1@\2/p"`)
if [ "${#supported_resolution_list[*]}" -eq 0 ]; then
	echo -n > ${temp_path}/qtdisplay.json
	systemctl stop display
else
	filecontent="$(cat ${temp_path}/qtdisplay.json)"

	APPLIANCE_RESOLUTION=${supported_resolution_list[0]/@*}
	APPLIANCE_REFRESH_RATE=${supported_resolution_list[0]/*@}
	shopt -s extglob
	if [ ${APPLIANCE_RESOLUTION} != "1920x1080" ]; then
		compatible_resolution_list=(${supported_resolution_list[*]/!(1280x720@*)})
		if [ -n "${compatible_resolution_list[*]}" ]; then
			APPLIANCE_RESOLUTION=1280x720
			APPLIANCE_REFRESH_RATE=${compatible_resolution_list[0]/*@}
		fi
	fi
	shopt -u extglob

	cachecontent="$(cat <<- END
	{
	  "device": "/dev/dri/card0",
	  "hwcursor": false,
	  "pbuffers": true,
	  "outputs": [
	    { "name": "HDMI1", "mode": "${APPLIANCE_RESOLUTION}@${APPLIANCE_REFRESH_RATE}", "size": "${APPLIANCE_RESOLUTION}", "format": "rgb565" },
		{ "name": "DVI1", "mode": "${APPLIANCE_RESOLUTION}@${APPLIANCE_REFRESH_RATE}", "size": "${APPLIANCE_RESOLUTION}", "format": "rgb565" }
	  ]
	}
	END
	)"

	if [ "$filecontent" != "$cachecontent" ]; then
		echo "$cachecontent" > ${temp_path}/qtdisplay.json
		export APPLIANCE_RESOLUTION APPLIANCE_REFRESH_RATE
		systemctl stop display
		systemctl set-environment APPLIANCE_RESOLUTION=${APPLIANCE_RESOLUTION} APPLIANCE_REFRESH_RATE=${APPLIANCE_REFRESH_RATE}
		systemctl --no-block start display
	fi
fi
