#!/bin/env sh

volume() {
	pactl get-sink-volume @DEFAULT_SINK@ | rg 'Volume: front-left:\s+\d+\s+/\s+(\d+)%' -or '$1' --color=never
}

mute() {
	if [[ "$(pactl get-sink-mute @DEFAULT_SINK@)" =~ 'yes' ]]; then
		echo "true"
	else
		echo "false"
	fi
}

get_device_id() {
	~/.config/eww/scripts/get-audio-device-id "$1"
}

HEADPHONES=""
HEADPHONES_ICON='󰋋'
SPEAKERS=""
SPEAKERS_ICON='󰓃'
HEADPHONE_MIC=""
HEADPHONE_MIC_ICON='󰋎'
BLUE_MIC=""
BLUE_MIC_ICON=''
UNKNOWN_ICON='?'

get_ids() {
	HEADPHONES="$(get_device_id 'headphones')"
	SPEAKERS="$(get_device_id 'speakers')"
	HEADPHONE_MIC="$(get_device_id 'headphone_mic')"
	BLUE_MIC="$(get_device_id 'blue_mic')"
}

audio_sink() {
	case "$(pactl get-default-sink)" in
		"$HEADPHONES") echo $HEADPHONES_ICON
		;;
		"$SPEAKERS") echo $SPEAKERS_ICON
		;;
		*) echo $UNKNOWN_ICON
		;;
	esac
}

audio_source() {
	case "$(pactl get-default-source)" in
		"$HEADPHONE_MIC") echo $HEADPHONE_MIC_ICON
		;;
		"$BLUE_MIC") echo $BLUE_MIC_ICON
		;;
		*) echo $UNKNOWN_ICON
		;;
	esac
}

audio() {
	echo "{\"volume\":$(volume),\"muted\":$(mute),\"sink\":\"$(audio_sink)\",\"source\":\"$(audio_source)\"}"
}

get_ids
audio
sleep 3
get_ids
audio
pactl subscribe | while read -r LINE; do
	if [[ "$LINE" =~ 'change' ]]; then
		audio
		get_ids
	fi
done

