#!/usr/bin/env bash

function get_time_ms {
  date -u +%s%3N
}

volicons=("󰕿" "󰖀" "󰕾")

vol() {
  wpctl get-volume @DEFAULT_AUDIO_"$1"@ | awk '{print int($2*100)}'
}
ismuted() {
  wpctl get-volume @DEFAULT_AUDIO_"$1"@ | rg -qi muted
  echo -n $?
}
setvol() {
  wpctl set-volume @DEFAULT_AUDIO_"$1"@ "$(awk -v n="$2" 'BEGIN{print (n / 100)}')"
}
setmute() {
  wpctl set-mute @DEFAULT_AUDIO_"$1"@ toggle
}

gen_output() {
  percent="$(vol "SINK")"
  lvl=$(awk -v n="$percent" 'BEGIN{print int(n/34)}')
  ismuted=$(ismuted "SINK")

  if [ "$ismuted" = 1 ]; then
    icon="${volicons[$lvl]}"
  else
    icon="󰝟"
  fi

  echo '{"icon": "'$icon'", "percent": '$(vol "SINK")', "microphone": '$(vol "SOURCE")'}'
}

if [ "$1" = "mute" ]; then
  if [ "$2" != "SOURCE" ] && [ "$2" != "SINK" ]; then
    echo "Can only mute SINK or SOURCE"
    exit 1
  fi
  setmute "$2"
elif [ "$1" = "setvol" ]; then
  if [ "$2" != "SOURCE" ] && [ "$2" != "SINK" ]; then
    echo "Can only set volume for SINK or SOURCE"
    exit 1
  elif [ "$3" -lt 0 ] || [ "$3" -gt 100 ]; then
    echo "Volume must be between 0 and 100"
    exit 1
  fi
  setvol "$2" "$3"
else
  last_time=$(get_time_ms)
  gen_output

  pw-cli -m 2>/dev/null | rg --line-buffered "PipeWire:Interface:Client" | while read -r event; do
    current_time=$(get_time_ms)
    delta=$((current_time - last_time))
    if [[ $delta -gt 50 ]]; then
      gen_output
      last_time=$(get_time_ms)
    fi
  done
fi
