#!/bin/sh

# Loop over pulseaudio sinks
sinks=$(pactl list short sinks)

while IFS= read -r line; do

    sink_name=$(echo "$line" | awk '{print $2}')
    sink_id=$(echo "$line" | awk '{print $1}')

    # Check HDMI connected status
    if echo "$sink_name" | grep -qi "HDMI"; then
        echo "HDMI sink found: $sink_name"

        hdmi_status="$(cat /sys/class/drm/card*HDMI*/status)"
        if [ $? -ne 0 ]; then
            echo "Unknown HDMI status...skipping"
            continue
        fi

        if [ "$hdmi_status" = "connected" ]; then
            echo "HDMI status: connected, selecting"
            default_sink=$sink_id
            break
        else
            echo "HDMI status: disconnected"
            continue
        fi
    fi

    # Select next non-null sink
    if echo "$sink_name" | grep -qiv "NULL"; then
        echo "Non-null sink found: $sink_name"
        default_sink=$sink_id
        break
    fi

done <<< "$sinks"

if [ ! -z $default_sink ]; then
    echo "Selecting default sink: $sink_name"
    pactl set-default-sink $default_sink
else
    echo "No default sink found, using NULL sink"
    pactl load-module module-null-sink sink_name=NULL > /dev/null 2>&1
    pactl set-default-sink NULL
fi
