#!/bin/sh

. /etc/control.d/functions

CONFIG=/etc/X11/gdm/custom.conf
SECTION=xdmcp
KEY=Enable

control_inifile_boolkey_status()
{
	local FILE=$1 SECTION=$2 KEY=$3
	local ENABLED="$(awk -F= "
		BEGIN { enabled=\"false\" }
		/^\[$SECTION]/ { section=1; next }
		/^\[.*]/ { if (section==1) section=0 }
		/^$KEY=.*/ {if (section==1) {enabled=\$2; exit} }
		END {print enabled}" <$CONFIG)"
	
	case "$ENABLED" in
		true)
			echo "enabled"
			;;
		false)
			echo "disabled"
			;;
		*)
			echo "unknown"
	esac
}

control_inifile_key()
{
	local FILE="$1" REQUEST="$2" VALUE=

	case "$REQUEST" in
	help|'help '*)
		control_help "${REQUEST#help}"
		;;
	list)
		control_list
		;;
	status)
		control_inifile_boolkey_status "$FILE" "$SECTION" "$KEY"
		;;
	summary)
		control_summary
		;;
	*)
		if ! printf %s "$REQUEST" | grep -q '^[a-z0-9_]*$'; then
			echo_error "Invalid mode: $REQUEST"
			return 1
		fi
		if [ "$(control_inifile_boolkey_status "$FILE" "$SECTION" "$KEY")" = "$REQUEST" ]; then
			return
		fi
		case "$REQUEST" in
			enabled)
				VALUE=true
				;;
			disabled)
				VALUE=false
				;;
			*)
				echo_error "Unavailable mode: $REQUEST"
				return 1
		esac
		# The following sed program searches $SECTION and replaces $KEY line(s)
		# in it with a new value. If there are no $KEY lines, a new line is
		# created.
		subst "
			/^\[$SECTION]/,/^\[[A-Za-z]\+]/ {
				/^\[$SECTION]/ {p;D}
				H
				/^\[[A-Za-z]\+]/ {
					g
					s|\(.*\n\)\($KEY=.*\n\)\?\(.*\)|\1$KEY=$VALUE\n\3|m
				}
				D
			}" /etc/X11/gdm/custom.conf 
		;;
	esac
}

new_help enabled 'Enable XDMCP access to GDM'
new_help disabled 'Disable XDMCP access to GDM'

new_summary 'XDMCP access to GDM'

control_inifile_key "$CONFIG" "$*"
