#!/usr/bin/env bash
# Parasite Eve native port — Day 1 preview launcher.
#   ./parasite-eve-preview "/path/to/Parasite Eve (USA) (Disc 1).bin" [extra args]
# Extra args are passed to the binary (e.g. --scale 4).
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [[ $# -lt 1 || "$1" == "-h" || "$1" == "--help" ]]; then
    echo "usage: $0 \"/path/to/Parasite Eve (USA) (Disc 1).bin\" [extra args]" >&2
    echo "       see README-PREVIEW.txt for controls" >&2
    exit 2
fi
DISC="$1"; shift
if [[ -d "$DISC" ]]; then
    found="$(find "$DISC" -maxdepth 2 -iname '*disc 1*.bin' -print -quit 2>/dev/null || true)"
    [[ -n "$found" ]] || found="$(find "$DISC" -maxdepth 2 -iname '*.bin' -print -quit 2>/dev/null || true)"
    DISC="$found"
fi
if [[ "$DISC" == *.cue || "$DISC" == *.CUE ]]; then
    bin="$(sed -n 's/^[[:space:]]*FILE[[:space:]]*"\(.*\)".*/\1/p' "$DISC" | head -n1)"
    [[ -n "$bin" ]] && DISC="$(dirname "$DISC")/$bin"
fi
[[ -n "$DISC" && -f "$DISC" ]] || { echo "ERROR: disc image not found: ${DISC:-$1}" >&2; exit 1; }
size="$(stat -L -c%s "$DISC")"   # -L: the image may be a symlink
if (( size % 2352 != 0 )); then
    echo "ERROR: $DISC is not a raw 2352-byte/sector BIN (size $size)." >&2
    echo "       Use the .bin from a BIN/CUE dump of Disc 1 (not .iso/.chd)." >&2
    exit 1
fi
if [[ -z "${DISPLAY:-}" ]]; then
    echo "ERROR: no X display (DISPLAY is unset). Run from a desktop session;" >&2
    echo "       on Wayland (KDE/GNOME/gamescope) XWayland provides DISPLAY." >&2
    exit 1
fi
cd "$HERE"
SKIP=()
[[ "${PE_SKIP_MOVIE:-0}" == 1 ]] && SKIP=(--skip-movie)
# Dev menu (Back/View + Start/Menu on a controller, F8 on the keyboard): on for
# checkpoint builds packaged with PE_PREVIEW_DEV_MENU=1; PE_DEV_MENU=0 turns it off.
export PE_DEV_MENU="${PE_DEV_MENU:-0}"
exec "$HERE/bin/parasite-eve-port" --windowed "${SKIP[@]}" --scale 3 \
    --window-title "Parasite Eve - Day 1 preview" \
    --disc-image "$DISC" "$@"
