#!/usr/bin/env bash
# JA3 без GOG Galaxy: подготовка bottle + подсказка по offline installer.
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "=== Jagged Alliance 3 без GOG Galaxy ==="
echo "Док: docs/games/JA3_MAC_WITHOUT_GALAXY.md"
echo ""

bash "${GOG_DIR}/emergency-stop.sh" || true

USED="$(bash -c 'source '"${GOG_DIR}"'/config.sh 2>/dev/null; gog_swap_used_mb' 2>/dev/null || echo 0)"
if [[ "${USED:-0}" -gt 400 ]] 2>/dev/null; then
  echo "❌ Swap ~${USED}MB — сначала перезагрузите Mac, затем снова этот скрипт."
  exit 1
fi

bash "${GOG_DIR}/setup-ja3-bottle.sh"

echo ""
echo "=== Скачайте offline installer (Windows) ==="
echo "  https://www.gog.com/account → Jagged Alliance 3"
echo "  → Download offline backup game installers (все части)"
echo ""
open "https://www.gog.com/account" 2>/dev/null || true

JA3_GAMES_DIR="${HOME}/Games"
ja3_bins_ok=1
for n in 1 2 3 4; do
  [[ -f "${JA3_GAMES_DIR}/setup_jagged_alliance_3_1.5.2_(80730)-${n}.bin" ]] || ja3_bins_ok=0
done
if [[ "${ja3_bins_ok}" -eq 1 ]]; then
  echo "Найдены 4× .bin в ${JA3_GAMES_DIR} — multipart offline backup."
  if [[ -f "${JA3_GAMES_DIR}/setup_jagged_alliance_3_1.5.2_(80730).exe" ]] \
    || find "${JA3_GAMES_DIR}" -maxdepth 1 -iname 'setup*jagged*alliance*3*.exe' -print -quit 2>/dev/null | grep -q .; then
    echo "Запуск install-ja3-innoextract.sh (innoextract, без Wine-Inno) …"
    exec bash "${GOG_DIR}/install-ja3-innoextract.sh"
  fi
  echo "❌ Не хватает лаунчера .exe (~1 MB) рядом с .bin."
  echo "   Скачайте с https://www.gog.com/account или:"
  echo "   bash ${GOG_DIR}/fetch-ja3-setup-exe.sh"
  exit 1
fi

# Автоустановка, если installer уже в Downloads
found=()
while IFS= read -r -d '' f; do
  found+=("$f")
done < <(find "${HOME}/Downloads" -maxdepth 1 -iname 'setup*jagged*alliance*3*.exe' -print0 2>/dev/null)

if [[ ${#found[@]} -eq 0 ]]; then
  echo "Когда .exe скачан (или все 5 частей в ~/Games):"
  echo "  bash ${GOG_DIR}/install-ja3-offline.sh ~/Downloads/setup_jagged_alliance_3_*.exe"
  echo "  bash ${GOG_DIR}/install-ja3-multipart.sh"
  exit 0
fi

echo "Найдены installers в Downloads:"
printf '  %s\n' "${found[@]}"
echo ""
for f in "${found[@]}"; do
  echo "Установка: ${f}"
  bash "${GOG_DIR}/install-ja3-offline.sh" "${f}" || exit 1
done
echo ""
echo "Запуск: bash ${GOG_DIR}/run-ja3.sh"
