#!/usr/bin/env bash

bluecard=$(pactl list cards | grep 'Name: bluez_card' | awk '{ print $2 }')

if [ "$1" = "fixbt" ] && [ -n "$bluecard" ]; then
  pactl set-card-profile "$bluecard" a2dp-sink
  exit
fi

hdmisink=$(pactl list sinks | grep 'Name: ' | grep hdmi | awk '{ print $2 }')
bluesink=$(pactl list sinks | grep 'Name: ' | grep bluez | awk '{ print $2 }')
analogsink=$(pactl list sinks | grep 'Name: ' | grep analog | awk '{ print $2 }')

currentsink=$(pactl get-default-sink)

case "$currentsink" in
  "$hdmisink") nextsink="${bluesink:-$analogsink}";;
  *) nextsink="$hdmisink";;
esac

pactl set-default-sink "$nextsink"

if [ "$nextsink" = "$bluesink" ]; then
  pactl set-card-profile "$bluecard" a2dp-sink
fi
