#!/usr/bin/env bash
# Довести установку JA3 через Wine-Inno (пост-скрипты GOG), если есть архивы в JA3_GAMES_DIR.
# innoextract одного не хватает для Lua/VFS — Wine-установщик создаёт правильный layout.
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"

JA3_GAMES_DIR="${JA3_GAMES_DIR:-${HOME}/Games}"
PREFIX='setup_jagged_alliance_3_1.5.2_(80730)'
EXE="${JA3_GAMES_DIR}/${PREFIX}.exe"
TARGET='C:\GOG Games\Jagged Alliance 3'

verify_archives() {
  [[ -f "${EXE}" ]] || {
    echo "❌ Нет ${EXE}"
    echo "   Положите 5 частей offline backup в ${JA3_GAMES_DIR}"
    exit 1
  }
  local n
  for n in 1 2 3 4; do
    [[ -f "${JA3_GAMES_DIR}/${PREFIX}-${n}.bin" ]] || {
      echo "❌ Нет ${JA3_GAMES_DIR}/${PREFIX}-${n}.bin"
      exit 1
    }
  done
}

main() {
  verify_archives
  bash "${GOG_DIR}/emergency-stop.sh" || true
  gog_swap_guard "${GOG_SWAP_MAX_MB:-800}" || exit 1
  gog_disk_guard 20 || exit 1

  export_wine_env_gog
  gog_wine_check

  local win
  win="$("${WINEPATH_BIN}" -w "${EXE}")"
  echo "Wine-установщик GOG (пост-скрипты, Lua.hpk)…"
  echo "  ${win}"
  cd "${JA3_GAMES_DIR}"
  if ! "${WINE64}" "${win}" /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /DIR="${TARGET}"; then
    echo "❌ Wine-Inno упал — см. docs/games/TROUBLESHOOTING.md § Setup gdi32"
    echo "   Запасной путь: innoextract + -unpacked (run-ja3.sh)"
    exit 1
  fi

  bash "${GOG_DIR}/finish-ja3-layout.sh"
  echo "OK. Запуск: bash ${GOG_DIR}/run-ja3.sh"
}

main "$@"
