#!/usr/bin/env bash
set -Eeuo pipefail

CUR_PATH="${HOME}/.cache/andreh/mpris-player.txt"

urldecode() { : "${*//+/ }"; echo -e "${_//%/\\x}"; }

default_status() {
  CUR="${1}"
  printf "%s: %s\n" "${CUR}" "$(playerctl --player="${CUR}" metadata --format "{{ title }} - {{ album }}")"
}

main() {
  CUR="$(cat "${CUR_PATH}")"
  if [[ "$(playerctl --player="${CUR}" status)" = "Paused" ]]; then
    printf "%s\n" "${CUR}"
  else
    case "${CUR}" in
      cmus)
        default_status "${CUR}"
        ;;
      firefox*)
        printf "%s: %s\n" "$(cut -d. -f1 <(echo "${CUR}"))" "$(playerctl --player="${CUR}" metadata --format "{{ title }}")"
        ;;
      vlc)
        # From URI encoded file:/// -> file name -> without extension -> with decoded URI -> drop timestamp
        NAME="$(basename "$(playerctl metadata xesam:url)")"
        FILE="$(urldecode "${NAME%.*}" | cut -d' ' -f2-)"
        printf "%s: %s\n" "${CUR}" "${FILE}"
        ;;
      *)
        default_status "${CUR}"
        ;;
    esac
  fi
}
export -f main

mkdir -p "$(dirname "${CUR_PATH}")"
touch "${CUR_PATH}"

while true
do
  main
  sleep 1
done
