#!/usr/bin/env bash
# Запуск GalaxySetup.exe (JA3 и др.) без родительского GalaxyInstaller — обход «Galaxy already running» + gdi32.
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"

PRODUCT_ID="${1:-1556263729}"
GAME_NAME="${2:-Jagged Alliance 3}"
LOG="/tmp/gog-galaxy-setup-${BOTTLE_NAME}.log"

gog_kill_all_galaxy() {
  pkill -f 'GOG_Galaxy_' 2>/dev/null || true
  pkill -f 'GalaxyWebInstaller' 2>/dev/null || true
  pkill -f 'GalaxyInstaller' 2>/dev/null || true
  pkill -f 'GalaxySetup' 2>/dev/null || true
  pkill -f "${BOTTLE_ID}.*Galaxy" 2>/dev/null || true
  sleep 2
}

find_galaxy_setup() {
  local d
  for d in "${BOTTLE_DIR}/drive_c/users/"*/AppData/Local/Temp/GalaxyInstaller_*; do
    [[ -f "${d}/GalaxySetup.exe" ]] || continue
    echo "${d}/GalaxySetup.exe"
    return 0
  done
  return 1
}

export_wine_env_gog_setup() {
  export WINEPREFIX="${BOTTLE_DIR}"
  export WINEMSYNC=1
  export WINEESYNC=1
  export DYLD_LIBRARY_PATH="${WINE_LIB}:${DYLD_LIBRARY_PATH:-}"
  # Inno/botva2: native gdiplus ломает gdi32 в MsgBox; stub/.NET — gdiplus=n,b
  export WINEDLLOVERRIDES="gdiplus=b"
  export WINEDEBUG="${WINEDEBUG:--all}"
  unset DXVK_ASYNC DXVK_HUD 2>/dev/null || true
}

main() {
  gog_wine_check

  if [[ ! -f "${BOTTLE_DIR}/.gog_galaxy_extract_installed" ]] \
    && ! find "${BOTTLE_DIR}/drive_c/Program Files"* -name 'GalaxyClient.exe' -print -quit 2>/dev/null | grep -q .; then
    echo "Сначала: bash ${GOG_DIR}/install-galaxy-extract.sh"
    exit 1
  fi

  local setup
  setup="$(find_galaxy_setup || true)"
  if [[ -z "${setup}" ]]; then
    echo "Нет GalaxySetup.exe в Temp. Сначала web-stub:"
    echo "  bash ${GOG_DIR}/run-web-installer.sh /path/GOG_Galaxy_*.exe"
    echo "Дождитесь скачивания ~277 MB, затем снова этот скрипт."
    exit 1
  fi

  gog_kill_all_galaxy
  export_wine_env_gog_setup

  local win="Z:${setup#${BOTTLE_DIR}}"
  win="${win//\//\\\\}"
  # Wine path: C:\users\...
  local cpath
  cpath="$("${WINEPATH_BIN}" -w "${setup}" 2>/dev/null || true)"
  if [[ -z "${cpath}" ]]; then
    cpath="C:\\users\\eternal\\AppData\\Local\\Temp\\$(basename "$(dirname "${setup}")")\\GalaxySetup.exe"
  fi

  echo "Setup: ${setup}"
  echo "Лог: ${LOG}"
  : >"${LOG}"

  "${WINE64}" "${cpath}" \
    /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /FORCECLOSEAPPLICATIONS /SP- \
    /lang=en_US /webinstaller "/product_id=${PRODUCT_ID}" "/game_name=${GAME_NAME}" \
    >>"${LOG}" 2>&1 &
  local pid=$!

  local i
  for i in $(seq 1 120); do
    sleep 5
    if ! kill -0 "${pid}" 2>/dev/null; then
      break
    fi
    if grep -qi 'Install successful\|Successfully installed' "${LOG}" 2>/dev/null; then
      break
    fi
  done

  gog_kill_all_galaxy

  local setup_log
  setup_log="$(find "${BOTTLE_DIR}/drive_c/users" -name 'Setup Log*.txt' -print 2>/dev/null | sort | tail -1)"
  if [[ -n "${setup_log}" ]]; then
    echo "--- Inno Setup log (tail) ---"
    tail -30 "${setup_log}"
  fi

  if grep -qi 'Install successful\|Successfully installed' "${setup_log:-/dev/null}" 2>/dev/null; then
    echo "OK: установка завершена."
    exit 0
  fi
  if grep -q 'Deinitializing Setup' "${setup_log:-/dev/null}" 2>/dev/null \
    && ! grep -q 'Access violation' "${setup_log:-/dev/null}" 2>/dev/null; then
    echo "OK: Setup завершился без AV (проверьте игру в Galaxy)."
    exit 0
  fi

  echo "Лог Wine:"
  tail -25 "${LOG}"
  exit 1
}

main "$@"
