#!/bin/bash

# pactl list sources | grep -e "Name" -e "Description"
# pactl set-default-source
# HiFi__Headphones__source -> laptop
# bluez_source -> bluetooth
# USB_Audio_Device -> usb headset
# usb-Synaptics -> usb-c headset
# <HDMI1/HDMI2/HDMI3>__source -> Screen
getFormalNameFromSink() {
    case "$1" in
        *HiFi__Headphones__source*)
            echo "Laptop mic"
            ;;
        *bluez*)
            echo "Bluetooth mic"
            ;;
        *usb-Synaptics*)
            echo "USB-c audio"
            ;;
        *USB*)
            echo "USB mic"
            ;;
        *pci*)
            echo "Core mic"
            ;;
        *Logitech*)
            echo "Logitech headset mic"
            ;;
        *)
            echo $1
            ;;
    esac
}

declare -A source_map
declare menu_options

readarray -t source_list < <(pactl list sources | grep -e "Name" | grep -e "input" | awk -F: '{print $2}')

for source in "${source_list[@]}"; do
    formal_name=$(getFormalNameFromSink $source)
    source_map["$formal_name"]="$source"
    if [[ ${#menu_options} -ne 0 ]]; then
        menu_options="$menu_options|"
    fi
    menu_options="$menu_options$formal_name"
done

chosen_option="$(rofi -no-config -no-lazy-grab -sep "|" -dmenu -i -p '󰍬 Audio input' -lines ${#source_list[@]} -no-fixed-num-lines -theme ~/.config/rofi/theme.rasi <<< "$menu_options")"

[[ "$chosen_option" == "" ]] && exit 0

chosen_source="${source_map["$chosen_option"]}"

pactl set-default-source $chosen_source

notify-send -t 3500 "Default Audio output" "$chosen_option"
