#!/usr/bin/env bash
set -euo pipefail

BASE_URL="${GOLF2K_BASE_URL:-https://golf.goudsmit.amsterdam}"
ZIP_NAME="de-hoge-dijk-compatibility-ladder-steamdeck.zip"
APP_ID="2385530"
EXPECTED_COUNT="25"

tmpdir="$(mktemp -d)"
cleanup() {
  rm -rf "$tmpdir"
}
trap cleanup EXIT

need_cmd() {
  command -v "$1" >/dev/null 2>&1 || {
    echo "Missing required command: $1" >&2
    exit 1
  }
}

need_cmd curl
need_cmd sha256sum
need_cmd unzip
need_cmd find
need_cmd cp

find_appmanifest() {
  local search_roots=(
    "$HOME/.local/share/Steam"
    "$HOME/.steam/steam"
    "/run/media"
    "/var/mnt"
  )
  for root in "${search_roots[@]}"; do
    [[ -d "$root" ]] || continue
    find "$root" -path "*/steamapps/appmanifest_${APP_ID}.acf" -print 2>/dev/null | head -n 1
  done | head -n 1
}

find_prefix() {
  if [[ -n "${GOLF2K_PFX:-}" ]]; then
    [[ -d "$GOLF2K_PFX" ]] || {
      echo "GOLF2K_PFX is set but does not exist: $GOLF2K_PFX" >&2
      exit 1
    }
    printf '%s\n' "$GOLF2K_PFX"
    return
  fi

  local search_roots=(
    "$HOME/.local/share/Steam"
    "$HOME/.steam/steam"
    "/run/media"
    "/var/mnt"
  )
  for root in "${search_roots[@]}"; do
    [[ -d "$root" ]] || continue
    find "$root" -path "*/steamapps/compatdata/${APP_ID}/pfx" -type d -print 2>/dev/null | head -n 1
  done | head -n 1
}

echo "Downloading De Hoge Dijk compatibility ladder..."
curl -fsSL "$BASE_URL/$ZIP_NAME" -o "$tmpdir/$ZIP_NAME"
curl -fsSL "$BASE_URL/SHA256SUMS-zip.txt" -o "$tmpdir/SHA256SUMS-zip.txt"
curl -fsSL "$BASE_URL/SHA256SUMS-courses.txt" -o "$tmpdir/SHA256SUMS-courses.txt"

(cd "$tmpdir" && sha256sum -c SHA256SUMS-zip.txt)
unzip -q "$tmpdir/$ZIP_NAME" -d "$tmpdir/extract"

course_count="$(find "$tmpdir/extract" -maxdepth 2 -name '*.course' | wc -l | tr -d ' ')"
if [[ "$course_count" != "$EXPECTED_COUNT" ]]; then
  echo "Expected $EXPECTED_COUNT .course files, found $course_count" >&2
  exit 1
fi

(cd "$tmpdir/extract/work" && sha256sum -c "$tmpdir/SHA256SUMS-courses.txt")

manifest="$(find_appmanifest || true)"
if [[ -n "$manifest" ]]; then
  echo "Found PGA TOUR 2K25 appmanifest: $manifest"
else
  echo "Could not find appmanifest_${APP_ID}.acf; continuing by searching Proton prefixes."
fi

pfx="$(find_prefix || true)"
if [[ -z "$pfx" ]]; then
  echo "Could not find Proton prefix for app ${APP_ID}." >&2
  echo "Set GOLF2K_PFX=/path/to/steamapps/compatdata/${APP_ID}/pfx and rerun." >&2
  exit 1
fi

target="$(find "$pfx" -path "*/Documents/My Games/PGA TOUR 2K25/Courses" -type d -print 2>/dev/null | head -n 1)"
if [[ -z "$target" ]]; then
  target="$pfx/drive_c/users/steamuser/Documents/My Games/PGA TOUR 2K25/Courses"
  mkdir -p "$target"
fi

cp "$tmpdir/extract/work/"*.course "$target/"
echo "Installed $EXPECTED_COUNT De Hoge Dijk ladder courses into:"
echo "$target"
echo
echo "Recommended next in-game test:"
echo "24_DeHogeDijk_post_smoke_fixes.course"
