#! /bin/bash
set -euo pipefail

have_cmd() { command -v "$1" >/dev/null 2>&1; }

# Always run from the directory this script lives in
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# ---- Find an x64sc-like binary ----
VICE_BIN=""

VICE_BIN=""

# ---- Preferred Mac local install ----
if [[ -x "$HOME/vice-acia/bin/x64sc" ]]; then
  VICE_BIN="$HOME/vice-acia/bin/x64sc"
fi

# ---- Otherwise search PATH ----
if [[ -z "$VICE_BIN" ]]; then
  for c in x64sc x64sc-sdl2 x64sc-gtk3 x64sc-gtk x64sc-sdl; do
    if have_cmd "$c"; then
      VICE_BIN="$c"
      break
    fi
  done
fi

if [[ -z "$VICE_BIN" ]]; then
  echo "ERROR: Not found - have you performed vicebuild.sh yet?"
  echo
  echo "Details:"
  echo " - Looked for: x64sc, x64sc-sdl2, x64sc-gtk3, x64sc-gtk, x64sc-sdl in PATH."
  echo " - If you installed VICE via Flatpak, the binary may not be on PATH."
  if have_cmd flatpak; then
    if flatpak list --app 2>/dev/null | grep -qi vice; then
      echo " - Flatpak appears to be installed and a VICE app may be present."
      echo "   See LTK Notes (line item #2) for Flatpak command guidance."
    fi
  fi
  exit 1
fi

echo "Using VICE binary: $VICE_BIN ($(command -v "$VICE_BIN"))"

# ---- Sanity-check required files (friendly failures) ----
need_file() {
  local f="$1"
  if [[ ! -f "$f" ]]; then
    echo "ERROR: Missing required file: $f"
    echo "Run this script from the LTK folder (or keep it in that folder)."
    exit 1
  fi
}

need_file "Config/config.ini"
need_file "Bins/ltk.crt"
need_file "DiskImages/ltkernal30-disk0.dlk"
need_file "DiskImages/ltkernal30-disk1.dlk"
need_file "DiskImages/ltkernal30-disk2.dlk"

# ---- Launch Vice ----
"$VICE_BIN" \
  -config "Config/config.ini" \
  -cartcrt "Bins/ltk.crt" \
  -ltkimage0 "DiskImages/ltkernal30-disk0.dlk" \
  -ltkimage1 "DiskImages/ltkernal30-disk1.dlk" \
  -ltkimage2 "DiskImages/ltkernal30-disk2.dlk"

# note! above command for "x64sc" may differ depending on your installation type of Vice.
# Look at shortcut that is normally used for Vice and ensure command is same.
# For flatpak installations of Vice, please refer to LTK Notes found at
# https://www.color64wiki.itchybutt.org/index.php/LTKNotes - line item #2.
