#!/usr/bin/env bash
# GOG Galaxy в Wine: логин в CEF ок, но auth.gog.com/token таймаут → сброс на пароль.
# Фиксы: IPv6 в Wine, сеть Poco/OpenSSL, CEF-флаги GOG.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
source "${SCRIPT_DIR}/config.sh"

cmd_wine_check() {
  if [[ ! -x "${WINE64}" ]]; then
    echo "Нет WhiskyWine: bash ${SCRIPT_DIR}/install-whiskywine-manual.sh"
    exit 1
  fi
}

cmd_wine_network_registry() {
  export WINEPREFIX="${BOTTLE_DIR}"
  echo "Wine: отключаю IPv6 DNS (частая причина зависания WinHTTP/Poco)…"
  "${WINE64}" reg add 'HKCU\Software\Wine\Network' /v DnsIPv6Enabled /t REG_DWORD /d 0 /f >/dev/null 2>&1 || true
  "${WINE64}" reg add 'HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings' \
    /v DisableIPv6 /t REG_DWORD /d 1 /f >/dev/null 2>&1 || true
  echo "Wine: ProxyEnable=0 (без системного прокси в bottle)…"
  "${WINE64}" reg add 'HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings' \
    /v ProxyEnable /t REG_DWORD /d 0 /f >/dev/null 2>&1 || true
}

cmd_dll_overrides() {
  export WINEPREFIX="${BOTTLE_DIR}"
  local key='HKCU\Software\Wine\DllOverrides'
  echo "Wine: DllOverrides для OpenSSL/Poco (native)…"
  for dll in libssl-1_1 libcrypto-1_1 libssl-3 libcrypto-3; do
    "${WINE64}" reg add "${key}" /v "${dll}" /t REG_SZ /d native,builtin /f >/dev/null 2>&1 || true
  done
}

cmd_clear_gog_webcache() {
  local cache="${BOTTLE_DIR}/drive_c/ProgramData/GOG.com/Galaxy/webcache"
  if [[ -d "${cache}" ]]; then
    rm -rf "${cache:?}"/*
    echo "Очищен webcache: ${cache}"
  fi
}

cmd_update_plist() {
  local ps="${BOTTLE_DIR}/Program Settings/GalaxyClient.exe.plist"
  local args
  args="$(homm_gog_cef_args_line)"
  if [[ -f "${ps}" ]]; then
    /usr/bin/plutil -replace arguments -string "${args}" "${ps}" 2>/dev/null \
      || echo "  (plist вручную: ${args})"
    echo "Обновлён ${ps}"
  fi
}

main() {
  cmd_wine_check
  if ! homm_gog_exe >/dev/null; then
    echo "GOG не установлен: bash ${SCRIPT_DIR}/start.sh gog-install"
    exit 1
  fi
  cmd_wine_network_registry
  cmd_dll_overrides
  cmd_clear_gog_webcache
  cmd_update_plist
  echo ""
  echo "OK. Перезапуск GOG:"
  echo "  bash ${SCRIPT_DIR}/start.sh gog-restart"
  echo ""
  echo "Если снова сброс на пароль — соберите логи:"
  echo "  bash ${SCRIPT_DIR}/diagnose-gog-auth.sh"
  echo ""
  echo "Проверка в логе после входа: НЕ должно быть «timeout … auth.gog.com/token»."
}

main "$@"
