#!/bin/sh
set -eu

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

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

if [ -z "$CURRENT_PLAYER" ]; then
  pick_first
elif ! echo "$AVAILABLE_PLAYERS" | grep -q "$CURRENT_PLAYER"; 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" | awk -v idx="$INDEX" 'NR == idx+1 {print}' > "$CURRENT_PLAYER_PATH"
  fi
fi

sh ~/dev/libre/dotfiles/xmonad/scripts/playerctl-play-pause.sh --refresh-only
