#!/bin/sh
#set -x

DEF_SINK=`pactl info | grep "Default Sink" | cut -d ":" -f 2 | tr -d ' '`

if [ ! `echo $DEF_SINK | grep -c hdmi` -eq 1 ]; then
	AVAILABLE_PORT=`pactl list cards | grep "\-output" | grep -v hdmi | grep priority | grep -v "not available" | wc -l`
	if [ "$AVAILABLE_PORT" = "0" ]; then
		HDMI_AVAILABLE_PORT=`pactl list cards | grep hdmi-output | grep priority | grep -v "not available" | wc -l`
		if [ ! "$HDMI_AVAILABLE_PORT" = "0" ]; then
			SINK_NUM=`pactl list sinks | grep "Sink #" | wc -l`
			if [ "$SINK_NUM" = "1" ]; then
				PROFILE=`pactl list cards | grep "output:hdmi-stereo+input:analog-stereo" | grep "available: yes" | wc -l`
				if [ ! "$PROFILE" = "0" ]; then
					echo "pactl set-card-profile 0 output:hdmi-stereo+input:analog-stereo"
					/usr/bin/pactl set-card-profile 0 output:hdmi-stereo+input:analog-stereo
				fi
			else
				HDMI_SINK=`pactl list sinks | grep "Name:" | cut -d ":" -f 2 | tr -d ' ' | grep hdmi -m 1`
				if [ `echo $HDMI_SINK | grep -c hdmi` -eq 1 ]; then
					echo "pactl set-default-sink $HDMI_SINK"
					/usr/bin/pactl set-default-sink $HDMI_SINK
				fi
			fi
		fi
	fi
fi
