#!/usr/bin/env bash
# JA3 из GOG offline backup installer — без Galaxy. Inno /VERYSILENT.
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"
GAMES_DIR="$(cd "${GOG_DIR}/.." && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"

INSTALLER="${1:-}"
LOG="/tmp/ja3-offline-install-${BOTTLE_NAME}.log"

usage() {
  cat <<EOF
Использование: bash $0 /path/to/setup_jagged_alliance_3_*.exe

Скачать (Windows offline backup):
  https://www.gog.com/account → Jagged Alliance 3 → Download offline backup game installers

Документация: docs/games/JA3_MAC_WITHOUT_GALAXY.md
EOF
}

if [[ -z "${INSTALLER}" || ! -f "${INSTALLER}" ]]; then
  usage
  exit 1
fi

bash "${GOG_DIR}/emergency-stop.sh"
gog_swap_guard "${GOG_SWAP_MAX_MB:-400}" || exit 1
gog_disk_guard 40 || {
  echo "❌ Для JA3 нужно ~40+ GB свободно на Data (игра + установка)."
  exit 1
}

export_wine_env_gog
gog_wine_check

# Inno silent (GOG offline installers)
SILENT=(/VERYSILENT /SUPPRESSMSGBOXES /NORESTART)
local_base="$(basename "${INSTALLER}")"
cp -f "${INSTALLER}" "${BOTTLE_DIR}/drive_c/${local_base}"

win="C:\\${local_base}"
echo "Установка JA3 (без Galaxy): ${INSTALLER}"
echo "Лог: ${LOG}"
: >"${LOG}"

cd "${BOTTLE_DIR}/drive_c"
if ! "${WINE64}" "${win}" "${SILENT[@]}" >>"${LOG}" 2>&1; then
  echo "❌ Установщик завершился с ошибкой. tail:"
  tail -40 "${LOG}"
  exit 1
fi

if [[ -f "${BOTTLE_DIR}/drive_c/GOG Games/Jagged Alliance 3/JA3.exe" ]]; then
  date -u +"%Y-%m-%dT%H:%M:%SZ" >"${BOTTLE_DIR}/.ja3_installed"
  echo ""
  echo "OK: JA3 установлен."
  echo "  Запуск: bash ${GOG_DIR}/run-ja3.sh"
else
  echo "⚠️  JA3.exe пока не найден — проверьте лог, возможно нужны ещё offline .exe (DLC/base):"
  tail -30 "${LOG}"
  exit 1
fi
