#!/bin/sh -e

# determine default output
ORIG_ASND=$(asoundconf get defaults.pcm.device || echo "0")
ORIG_GCONF=$(gconftool-2 -g /system/gstreamer/0.10/default/musicaudiosink)
ORIG_GCONF_DESC=$(gconftool-2 -g /system/gstreamer/0.10/default/musicaudiosink_description)

# determine HDMI output
HDMI_ASND=$(aplay -l | grep HDMI | sed -ne 's/.*, device \([0-9]\+\):.*/\1/p' | head -n1)
[ "$HDMI_ASND" = "" ] && exit 0
HDMI_GCONF="halaudiosink udi=$(hal-find-by-property --key alsa.type --string playback | grep _${HDMI_ASND})"
hdmi_gconf_udi=$(echo $HDMI_GCONF | sed -ne 's/.*udi=//p')
HDMI_GCONF_DESC=$(hal-get-property --udi "$hdmi_gconf_udi" --key alsa.device_id)


while [ -e /proc/dri/sdvo/hotplug ]; do
	# this puts us to sleep until we get a hotplug event
	cat /proc/dri/sdvo/hotplug > /dev/null

	# give X's RandR a second to finish updating the resolution
	sleep 1

	connected="$(xrandr -q | grep TMDS | grep -v disconnected || true)"
	if [ "$connected" = "" ]; then

		# disconnected from HDMI
		asoundconf set defaults.pcm.device $ORIG_ASND
		gconftool-2 --type string -s /system/gstreamer/0.10/default/musicaudiosink "$ORIG_GCONF"
		gconftool-2 --type string -s /system/gstreamer/0.10/default/musicaudiosink_description "$ORIG_GCONF_DESC"

	else

		# connected to HDMI device
		asoundconf set defaults.pcm.device $HDMI_ASND
		gconftool-2 --type string -s /system/gstreamer/0.10/default/musicaudiosink "$HDMI_GCONF"
		gconftool-2 --type string -s /system/gstreamer/0.10/default/musicaudiosink_description "$HDMI_GCONF_DESC"

	fi
done

exit 0
