#!/bin/bash
# Hockey auto‑resume player – native VLC first, Flatpak fallback; HW‑optimised
VIDEO_DIR="/mnt/crow/videos/Hockey"
TIME_FILE="/tmp/vlc-last-time"
SEEK_BACK=5

# --------------------------------------------------------------------
# 1. Locate a working VLC (native → Flatpak → exit)
# --------------------------------------------------------------------
if command -v vlc &>/dev/null; then
    VLC_BIN="vlc"
    USE_FLATPAK=0
elif command -v flatpak &>/dev/null && flatpak info org.videolan.VLC &>/dev/null; then
    VLC_BIN="org.videolan.VLC"
    USE_FLATPAK=1
else
    echo "VLC not found. Install it natively or via Flatpak." >&2
    exit 1
fi

# --------------------------------------------------------------------
# 2. Performance options – suitable for RPi5, Sandy Bridge, modern PCs
# --------------------------------------------------------------------
# Allow user override with the environment variable VLC_PERF_OPTS.
if [ -z "$VLC_PERF_OPTS" ]; then
    # --avcodec-hw=any    → enable hardware decoding (VAAPI, V4L2, etc.)
    # --no-osd            → disable on‑screen display (save CPU on weak hardware)
    # --no-mouse-events   → ignore mouse input while playing
    # --no-snapshot-preview → skip thumbnail creation
    VLC_PERF_OPTS="--avcodec-hw=any --no-osd --no-mouse-events --no-snapshot-preview --fullscreen"
fi

# --------------------------------------------------------------------
# 3. Video directory & file selection
# --------------------------------------------------------------------
if [ ! -d "$VIDEO_DIR" ]; then
    echo "Directory $VIDEO_DIR not found." >&2
    exit 1
fi

mapfile -t FILES < <(find "$VIDEO_DIR" -maxdepth 1 -type f -name "*.ts" -printf "%f\n" | sort)
if [ ${#FILES[@]} -eq 0 ]; then
    echo "No .ts files in $VIDEO_DIR." >&2
    exit 1
fi

echo "Available .ts files in $VIDEO_DIR:"
select file in "${FILES[@]}"; do
    if [ -n "$file" ]; then
        FULL_PATH="$VIDEO_DIR/$file"
        echo "Selected: $FULL_PATH"
        break
    else
        echo "Invalid choice."
    fi
done

# --------------------------------------------------------------------
# 4. Cleanup & time‑logging preparation
# --------------------------------------------------------------------
: > "$TIME_FILE"                          # ensure an empty time file

if ! command -v playerctl &>/dev/null; then
    echo "Warning: playerctl not found – playback position won't be saved." >&2
fi

# Trap signals and kill the background time‑logger and VLC
trap 'kill "$STORE_PID" 2>/dev/null; kill "$VLC_PID" 2>/dev/null; exit' INT TERM

# --------------------------------------------------------------------
# 5. Main loop – play, log time, restart on exit
# --------------------------------------------------------------------
while true; do
    # Determine start time
    LAST_TIME=0
    if [ -f "$TIME_FILE" ] && grep -qE '^[0-9]+' "$TIME_FILE"; then
        LAST_TIME=$(cut -d' ' -f1 "$TIME_FILE")
    fi
    if [ "$LAST_TIME" -gt "$SEEK_BACK" ] 2>/dev/null; then
        START_TIME=$(( LAST_TIME - SEEK_BACK ))
    else
        START_TIME=0
    fi

    echo "Starting VLC..."
    if [ "$USE_FLATPAK" -eq 1 ]; then
        flatpak run --filesystem="$VIDEO_DIR" --filesystem=/tmp \
            "$VLC_BIN" $VLC_PERF_OPTS --start-time="$START_TIME" --play-and-exit "$FULL_PATH" &
    else
        "$VLC_BIN" $VLC_PERF_OPTS --start-time="$START_TIME" --play-and-exit "$FULL_PATH" &
    fi
    VLC_PID=$!

    # Background logger – writes current playback position every second
    (
        while kill -0 "$VLC_PID" 2>/dev/null; do
            if command -v playerctl &>/dev/null; then
                # Try the usual MPRIS name for VLC (lowercase)
                POS=$(playerctl -p vlc position-raw 2>/dev/null || true)
                # If that failed, try the capitalised name sometimes used by Flatpak
                if [ -z "$POS" ]; then
                    POS=$(playerctl -p VLC position-raw 2>/dev/null || true)
                fi
                if [[ "$POS" =~ ^[0-9]+([.][0-9]+)?$ ]]; then
                    echo "${POS%%.*}" > "$TIME_FILE"
                fi
            fi
            sleep 1
        done
    ) &
    STORE_PID=$!

    # Wait for VLC to finish, then stop the logger
    wait "$VLC_PID" 2>/dev/null
    kill "$STORE_PID" 2>/dev/null || true
    wait "$STORE_PID" 2>/dev/null || true

    echo "VLC exited. Restarting..."
done
