#!/bin/sh
# The general mp3/mp4 player. Installed to /usr/local/bin/media-player.
#
# mpv, same as the thin client's — it plays everything without a codec pack, it exposes
# MPRIS through mpv-mpris (which is what puts the transport controls in Home Assistant
# and on the remote's media keys), and it takes a file, a directory or a URL equally.
#
# --idle=yes --force-window is what makes it part of a *session* rather than a one-shot
# command: with no file given it opens an empty player window and waits, so it is
# already on 4:media with a working MPRIS bus before anyone has picked something to
# play. Dropping a file on it, opening one from a share, or `media-player <path>` from
# the maintenance shell all then load into the window that is already there.
#
# The "media-player-idle" title is not decoration — media-session and the sway config
# both match on it (mpv's app_id is just "mpv", which a second, file-playing mpv would
# share), so changing it means changing those two too.
set -eu

# A second invocation with a file loads it into the running instance rather than
# opening a competing window: two mpvs means two MPRIS players and a coin-flip as to
# which one the remote's play button reaches. mpv.conf sets input-ipc-server for this.
SOCKET="${HOME:-/home/$(id -un)}/.mpv-socket"

if [ -n "${1:-}" ] && [ -S "$SOCKET" ]; then
  # loadfile via the JSON IPC. The path is passed as a JSON string argument, never
  # interpolated into a shell command.
  if printf '{"command":["loadfile","%s","replace"]}\n' "$1" | socat - "$SOCKET" 2>/dev/null; then
    exit 0
  fi
  # If that failed the socket is stale (mpv died without cleaning up) — fall through to
  # a plain launch, which is the right outcome rather than an error.
fi

if [ -n "${1:-}" ]; then
  exec mpv --title=media-player-idle "$@"
fi

exec mpv --idle=yes --force-window=yes --title=media-player-idle
