#!/bin/bash
# DVDplay a simple DVD Player using yad and mpv.
# Concept and Testing by Glen MacArthur, coded by Google Gemini 3.

# 1. Capture the input exactly
RAW_INPUT="$1"

if [ -z "$RAW_INPUT" ]; then
    TARGET="dvd://"
    DEVICE="/dev/sr0"
    DISPLAY_NAME="Physical Disc"
else
    TARGET="dvd://"
    DEVICE=$(realpath "$RAW_INPUT")
    DISPLAY_NAME="${RAW_INPUT##*/}"
fi

PIPE="$HOME/.dvd-socket"

# Clean start
pkill -f "mpv dvd://"
rm -f "$PIPE"

# 2. Start Engine 
mpv "$TARGET" --dvd-device="$DEVICE" --input-ipc-server="$PIPE" \
    --idle=yes --force-window=yes \
    --deinterlace=yes --video-sync=display-resample \
    --volume=100 --af=loudnorm &

# 3. The Remote
# Skip buttons now use "add chapter" which works with the dvd:// protocol
yad --title="DVD Player" --window-icon="/usr/local/share/icons/custom/cdplayer.png" --width=480 --center \
    --no-esc \
    --text="<b>Playing:</b> $DISPLAY_NAME" --text-align=center \
    --form --columns=3 \
    --field="!media-skip-backward!:FBTN" "bash -c 'echo \"add chapter -1\" | socat - \"$PIPE\"'" \
    --field="!media-playback-start!:FBTN" "bash -c 'echo \"cycle pause\" | socat - \"$PIPE\"'" \
    --field="!media-skip-forward!:FBTN" "bash -c 'echo \"add chapter 1\" | socat - \"$PIPE\"'" \
    --field="!media-view-subtitles!:FBTN" "bash -c 'echo \"cycle sub\" | socat - \"$PIPE\"'" \
    --field="!media-optical-menu!:FBTN" "bash -c 'echo \"discnav menu\" | socat - \"$PIPE\"'" \
    --field="!audio-speakers!:FBTN" "bash -c 'echo \"cycle audio\" | socat - \"$PIPE\"'" \
    --field="Title Number:NUM" "1!1..99!1" \
    --field="Jump to Title:FBTN" "bash -c 'VAL=\$(echo %7 | cut -d. -f1); echo \"loadfile dvd://\$VAL\" | socat - \"$PIPE\"'" \
    --button="Fullscr:bash -c 'echo \"cycle fullscreen\" | socat - \"$PIPE\"'" \
    --button="Close:0"

# 4. Cleanup
pkill -f "mpv dvd://"
rm -f "$PIPE"