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

mkdir -p "${HOME}/.cache/andreh/"
CURRENT_PLAYER_PATH="${HOME}/.cache/andreh/mpris-player.txt"
AVAILABLE_PLAYERS="$(playerctl --list-all | sort)"
CURRENT_PLAYER="$(cat "${CURRENT_PLAYER_PATH}" ||:)"

pick_first() {
  echo "${AVAILABLE_PLAYERS}" | head -n 1 > "${CURRENT_PLAYER_PATH}"
}

if [[ "${CURRENT_PLAYER}" = "" ]]; then
  pick_first
elif ! echo "${AVAILABLE_PLAYERS}" | grep "${CURRENT_PLAYER}" > /dev/null; then
  # Unknown $CURRENT_PLAYER, pick anyone
  pick_first
else
  INDEX="$(echo "${AVAILABLE_PLAYERS}" | grep -n "${CURRENT_PLAYER}" | cut -d: -f1)"
  LENGTH="$(echo "${AVAILABLE_PLAYERS}" | wc -l)"
  if [[ "${INDEX}" = "${LENGTH}" ]]; then
    # Reached the end of the $AVAILABLE_PLAYERS list, wrapping
    pick_first
  else
    # Get the next player instead
    echo "${AVAILABLE_PLAYERS}" | cut -d$'\n' -f"$((INDEX + 1))" > "${CURRENT_PLAYER_PATH}"
  fi
fi
