#!/usr/bin/env bash
# Boots a disc image in PCSX2 on the host.
#
#   kz-pcsx2 <iso>
#
# Set PCSX2 to name the emulator outright. PCSX2 needs a display and a GPU,
# so this never runs in the build container.
set -euo pipefail

iso=${1:?usage: kz-pcsx2 <iso>}

if [ ! -f "$iso" ]; then
    echo "$iso does not exist; build the iso target first." >&2
    exit 1
fi
iso_dir=$(cd "$(dirname "$iso")" && pwd)
iso="$iso_dir/$(basename "$iso")"

# Sets EMU to the emulator command, as words.
find_pcsx2() {
    local candidate app appimage win_dir
    EMU=()
    if [ -f "${PCSX2:-}" ]; then
        EMU=("$PCSX2")
        return 0
    fi
    if [ -n "${PCSX2:-}" ]; then
        # shellcheck disable=SC2206  # word splitting is the point: PCSX2 may be a command line
        EMU=($PCSX2)
        return 0
    fi
    case $(uname -s) in
        MINGW*|MSYS*|CYGWIN*)
            if command -v pcsx2-qt.exe >/dev/null 2>&1; then
                EMU=("$(command -v pcsx2-qt.exe)")
                return 0
            fi
            win_dir=${PROGRAMFILES:-}
            if [ -n "$win_dir" ] && command -v cygpath >/dev/null 2>&1; then
                win_dir=$(cygpath -u "$win_dir")
            fi
            if [ -n "$win_dir" ] && [ -f "$win_dir/PCSX2/pcsx2-qt.exe" ]; then
                EMU=("$win_dir/PCSX2/pcsx2-qt.exe")
                return 0
            fi ;;
    esac
    for candidate in pcsx2-qt pcsx2 PCSX2; do
        if command -v "$candidate" >/dev/null 2>&1; then
            EMU=("$candidate")
            return 0
        fi
    done
    for app in /Applications/PCSX2.app "$HOME"/Applications/PCSX2.app; do
        if [ -x "$app/Contents/MacOS/PCSX2" ]; then
            EMU=("$app/Contents/MacOS/PCSX2")
            return 0
        fi
    done
    if command -v flatpak >/dev/null 2>&1 \
       && flatpak info net.pcsx2.PCSX2 >/dev/null 2>&1; then
        EMU=(flatpak run net.pcsx2.PCSX2)
        return 0
    fi
    for appimage in "$HOME"/Applications/PCSX2*.AppImage "$HOME"/Downloads/PCSX2*.AppImage; do
        if [ -x "$appimage" ]; then
            EMU=("$appimage")
            return 0
        fi
    done
    return 1
}

if ! find_pcsx2; then
    echo "PCSX2 not found. Install it, or point PCSX2 at the executable:" >&2
    echo "  PCSX2=/path/to/pcsx2-qt $0 $iso" >&2
    exit 1
fi

iso_arg=$iso
case $(uname -s) in
    MINGW*|MSYS*|CYGWIN*)
        if command -v cygpath >/dev/null 2>&1; then
            iso_arg=$(cygpath -w "$iso")
        fi ;;
esac

# -- ends PCSX2's own options so the image path is taken literally.
echo "Booting $iso in ${EMU[*]}"
exec "${EMU[@]}" -fastboot -- "$iso_arg"
