#!/bin/bash -e

lightdm_conf="/etc/lightdm/lightdm.conf"
display_setup_script_dir="/etc/pi-top/lightdm"
display_setup_script="$display_setup_script_dir/display-setup-script"
line_to_add="/usr/bin/xhost local:root"

error_help_print()
{
	echo "NOTE: User idle time detection will likely not be able to work"
	echo "See https://github.com/pi-top/Device-Management/ for more information on how to resolve this issue"
}

create_new_display_setup_script()
{
	mkdir -p "$display_setup_script_dir"
	# Avoid possible recursion
	if [[ "$existing_script" == "$display_setup_script" ]]; then
		existing_script=""
	fi
	cat << EOF > "$display_setup_script"
#!/bin/bash

$line_to_add
$existing_script
EOF
}

configure_display_setup_script()
{
	existing_script=$(grep "display\-setup\-script=" "$lightdm_conf" | awk -F "=" '{print $NF}')
	if [[ -f "$display_setup_script" ]]; then
		echo "$display_setup_script already exists"

		if grep -q "$line_to_add" "$display_setup_script"; then
			echo "xhost fix line detected - deleting..."
			sed -i "\|$line_to_add|d" "$display_setup_script"
		fi
		echo "$line_to_add" >> "$display_setup_script"
	else
		create_new_display_setup_script
	fi
	chmod +x "$display_setup_script"
}

configure_lightdm_conf()
{
	sed -i "s|.*display-setup-script=.*|display-setup-script=$display_setup_script|1" "$lightdm_conf"
}

echo "User idle time detection requires non-network local connections to X server"
echo "Attempting to enable..."
if [[ -f "$lightdm_conf" ]]; then
	if grep -q "display-setup-script=" "$lightdm_conf"; then
		configure_display_setup_script
		configure_lightdm_conf
		echo "DONE. Reboot for this to take effect"
	else
		echo "Unable to find 'display-setup-script' in $lightdm_conf"
		error_help_print
	fi
else
	echo "Unable to find $lightdm_conf"
	error_help_print
fi
