#!/usr/bin/env bash
# GOG web-stub в отдельном GOG-bottle. Без Steam/HoMM.
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"
# shellcheck source=wine-fonts.sh
source "${GOG_DIR}/wine-fonts.sh"

GOG_SETUP_MARKER="${BOTTLE_DIR}/.gog_setup_v1"
LOG="/tmp/gog-web-installer-${BOTTLE_NAME}.log"

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

  Bottle: ${BOTTLE_NAME} (${BOTTLE_ID}) — только GOG, без Steam.
  Один раз: bash ${GOG_DIR}/use-bottle.sh <UUID>
            bash ${GOG_DIR}/setup-bottle.sh
            bash ${GOG_DIR}/install-corefonts.sh

  Лог: ${LOG}
EOF
}

gog_kill_installers() {
  pkill -f 'GOG_Galaxy_' 2>/dev/null || true
  pkill -f 'GalaxyWebInstaller' 2>/dev/null || true
  sleep 1
}

main() {
  local src="${1:-}"
  if [[ -z "${src}" || "${src}" == "-h" || "${src}" == "--help" ]]; then
    usage
    exit 0
  fi
  [[ -f "${src}" ]] || { echo "Нет файла: ${src}"; exit 1; }

  gog_wine_check
  gog_disk_guard 5 || exit 1

  if [[ ! -f "${BOTTLE_DIR}/.gog_gdiplus_installed" ]]; then
    echo "⚠️  Нет gdiplus — один раз: bash ${GOG_DIR}/install-gdiplus.sh"
  fi
  if [[ ! -f "${BOTTLE_DIR}/.gog_corefonts_installed" ]]; then
    echo "⚠️  Сначала: bash ${GOG_DIR}/install-corefonts.sh"
  fi

  [[ -f "${GOG_SETUP_MARKER}" ]] || bash "${GOG_DIR}/setup-bottle.sh"
  gog_wine_ensure_fonts 0

  local base dest_win
  base="$(basename "${src}")"
  dest_win="C:\\${base}"
  cp -f "${src}" "${BOTTLE_DIR}/drive_c/${base}"

  gog_kill_installers
  export_wine_env_gog

  echo "Bottle: ${BOTTLE_NAME}"
  echo "Запуск: ${dest_win}"
  echo "Лог: ${LOG}"

  : >"${LOG}"
  nohup "${WINE64}" "${dest_win}" >"${LOG}" 2>&1 &
  local i alive=0
  for i in 1 2 3 4 5 6; do
    sleep 2
    if pgrep -f "${base}" >/dev/null 2>&1; then
      alive=1
      break
    fi
  done

  if [[ "${alive}" -eq 1 ]]; then
    sleep 3
    if grep -q 'FontFamily could not be found' "${LOG}" 2>/dev/null; then
      echo "❌ FontFamily в логе — bash ${GOG_DIR}/install-gdiplus.sh && install-corefonts.sh"
      tail -5 "${LOG}"
      exit 1
    fi
    echo "OK: установщик запущен (Cmd+Tab → ${base})."
    exit 0
  fi
  if grep -q 'FontFamily could not be found' "${LOG}" 2>/dev/null; then
    echo "❌ FontFamilyNotFound:"
    tail -8 "${LOG}"
    exit 1
  fi
  echo "Процесс завершился:"
  tail -20 "${LOG}"
  exit 1
}

main "$@"
