#!/usr/bin/env bash
# GOG Galaxy 2.0: скачать официальный установщик и поставить в bottle HoMM-OldenEra.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
source "${SCRIPT_DIR}/config.sh"

SILENT="${GOG_INSTALL_SILENT:-0}"

if [[ ! -d "${BOTTLE_DIR}/drive_c" ]]; then
  echo "Bottle ещё не инициализирован."
  echo "1) open -a Whisky"
  echo "2) Откройте bottle «${BOTTLE_NAME}»"
  echo "3) Запустите этот скрипт снова"
  open -a Whisky
  exit 1
fi

if exe="$(homm_gog_exe)"; [[ -n "${exe}" ]]; then
  echo "GOG Galaxy уже установлен: ${exe}"
  echo "Запуск: bash ${SCRIPT_DIR}/start.sh gog"
  exit 0
fi

mkdir -p "${GAMES_CACHE_DIR}"

homm_gog_setup_url() {
  if [[ -n "${GOG_SETUP_URL:-}" ]]; then
    echo "${GOG_SETUP_URL}"
    return 0
  fi
  local json url
  json="$(curl -fsSL "https://remote-config.gog.com/components/webinstaller?component_version=2.0.0")"
  url="$(python3 -c 'import json,sys; d=json.load(sys.stdin); print(d["content"]["windows"]["downloadLink"])' <<<"${json}" 2>/dev/null)" || true
  if [[ -z "${url}" ]]; then
    url="https://content-system.gog.com/open_link/download?path=/open/galaxy/client/setup_galaxy_2.0.100.1.exe"
  fi
  echo "${url}"
}

if [[ ! -f "${GOG_SETUP}" ]]; then
  dl_url="$(homm_gog_setup_url)"
  echo "Скачиваю полный установщик GOG Galaxy (~290 MB)…"
  echo "  ${dl_url}"
  curl -L --fail --retry 3 -C - -o "${GOG_SETUP}" "${dl_url}"
fi

echo "Размер установщика: $(du -sh "${GOG_SETUP}" | awk '{print $1}')"
min_gb="${HOMM_DISK_MIN_GB:-3}"
min_kb=$((min_gb * 1024 * 1024))
if [[ "$(homm_disk_free_kb)" -lt "${min_kb}" ]]; then
  echo "❌ Мало места на диске (<${min_gb} GB). GOG Galaxy ~300+ MB."
  exit 1
fi

homm_gog_install_from_extract() {
  local extract_dir="${GAMES_CACHE_DIR}/gog-galaxy-extract"
  local gog_pf="${BOTTLE_DIR}/drive_c/Program Files (x86)/GOG Galaxy"
  local gog_pd="${BOTTLE_DIR}/drive_c/ProgramData/GOG.com/Galaxy"
  if ! command -v innoextract >/dev/null 2>&1; then
    echo "Нужен innoextract: brew install innoextract"
    return 1
  fi
  echo "Распаковка установщика (innoextract) — обход gdi32 в Wine-инсталляторе…"
  rm -rf "${extract_dir}"
  mkdir -p "${extract_dir}"
  innoextract -e -d "${extract_dir}" "${GOG_SETUP}"
  mkdir -p "${gog_pf}" "${gog_pd}"
  cp -R "${extract_dir}/app/." "${gog_pf}/"
  local pd_src
  pd_src="$(find "${extract_dir}" -type d -path '*/GOG.com/Galaxy' 2>/dev/null | head -1)"
  if [[ -n "${pd_src}" ]]; then
    cp -R "${pd_src}/." "${gog_pd}/"
  fi
  homm_gog_exe >/dev/null
}

export_wine_env_steam

# Wine Inno Setup часто падает на gdi32 в /VERYSILENT; по умолчанию — распаковка.
if [[ "${GOG_INSTALL_WINE:-0}" == "1" && "${SILENT}" == "1" ]]; then
  echo "Тихая установка через Wine (эксперимент)…"
  cp -f "${GOG_SETUP}" "${BOTTLE_DIR}/drive_c/setup_galaxy.exe" 2>/dev/null || true
  "${WINE64}" 'C:\\setup_galaxy.exe' /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /FORCECLOSEAPPLICATIONS /SP- || true
  sleep 10
elif [[ "${SILENT}" == "1" ]]; then
  homm_gog_install_from_extract || exit 1
else
  echo "Запуск GUI-установщика GOG Galaxy в bottle «${BOTTLE_NAME}»…"
  echo "Дождитесь завершения мастера установки, затем:"
  echo "  bash ${SCRIPT_DIR}/start.sh gog"
  if command -v whisky >/dev/null 2>&1; then
    whisky run "${BOTTLE_NAME}" "${GOG_SETUP}"
  else
    "${WINE64}" "${GOG_SETUP}"
  fi
  exit 0
fi

if exe="$(homm_gog_exe)"; [[ -n "${exe}" ]]; then
  echo "OK: GOG Galaxy → ${exe}"
  bash "${SCRIPT_DIR}/pin-gog-whisky.sh" 2>/dev/null || true
  echo "Запуск: bash ${SCRIPT_DIR}/start.sh gog"
else
  echo "GalaxyClient.exe не найден."
  echo "  GUI: GOG_INSTALL_SILENT=0 bash ${SCRIPT_DIR}/install-gog-galaxy.sh"
  echo "  Wine silent (часто ломается): GOG_INSTALL_WINE=1 GOG_INSTALL_SILENT=1 …"
  exit 1
fi
