#!/usr/bin/env bash
# Снимок логов GOG login + краткий разбор (auth.gog.com/token, refreshToken).
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
source "${SCRIPT_DIR}/config.sh"

LOGDIR="${BOTTLE_DIR}/drive_c/ProgramData/GOG.com/Galaxy/logs"
OUT="${GAMES_CACHE_DIR}/gog-auth-diagnose-$(date +%Y%m%d-%H%M%S)"
mkdir -p "${OUT}"

for f in GalaxyClient.log cef.log ClientHelper-Authentication.log GalaxyClientService.log; do
  [[ -f "${LOGDIR}/${f}" ]] && cp -f "${LOGDIR}/${f}" "${OUT}/"
done

{
  echo "=== $(date) ==="
  echo "Bottle: ${BOTTLE_NAME} (${BOTTLE_ID})"
  df -h "$(homm_data_volume_path)" | awk 'NR==2'
  echo ""
  echo "=== proxy (macOS) ==="
  scutil --proxy 2>/dev/null | head -12
  echo ""
  echo "=== GOG processes ==="
  pgrep -fl 'GalaxyClient' 2>/dev/null || echo "(none)"
  echo ""
  echo "=== refreshToken в реестре ==="
  export WINEPREFIX="${BOTTLE_DIR}"
  "${WINE64}" reg query 'HKCU\Software\GOG.com\Galaxy' /v refreshToken 2>&1 || echo "нет refreshToken"
  echo ""
  echo "=== последние auth-события (GalaxyClient.log) ==="
  grep -iE 'Authentication failed|auth\.gog\.com/token|refreshToken|on_login_success|timeout.*gog|API status' \
    "${LOGDIR}/GalaxyClient.log" 2>/dev/null | tail -25
  echo ""
  echo "=== CEF login (cef.log) ==="
  grep -iE 'ERROR|message from source|recaptcha|frame-ancestors' "${LOGDIR}/cef.log" 2>/dev/null | tail -15
  echo ""
  echo "=== Mac → auth.gog.com/token ==="
  curl -sS -o /dev/null -w "http:%{http_code} total:%{time_total}s\n" --max-time 15 \
    -X POST "https://auth.gog.com/token" \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -d "grant_type=authorization_code&client_id=x&code=x" 2>&1 || echo "curl FAIL"
} > "${OUT}/summary.txt"

echo "Архив: ${OUT}"
cat "${OUT}/summary.txt"
