#!/usr/bin/env bash
# Whisky Libraries Wine 11.0 → Gcenx wine-staging 11.9 + GPTK D3DMetal bridge (JA3 / D3D12).
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"
GAMES_DIR="$(cd "${GOG_DIR}/.." && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"

CACHE="${GAMES_CACHE_DIR}"
TAR="${CACHE}/wine-staging-11.9-osx64.tar.xz"
URL="https://github.com/Gcenx/macOS_Wine_builds/releases/download/11.9/wine-staging-11.9-osx64.tar.xz"
WHISKY_WINE="${WHISKY_LIBS}/Libraries/Wine"
STAMP="${WHISKY_LIBS}/Libraries/.wine_gcenx_11.9"

[[ -f "${TAR}" ]] || curl -L --fail -o "${TAR}" "${URL}"
EXTRACT="${CACHE}/wine-staging-11.9-extract"
rm -rf "${EXTRACT}"
mkdir -p "${EXTRACT}"
tar -xJf "${TAR}" -C "${EXTRACT}"
SRC="${EXTRACT}/Wine Staging.app/Contents/Resources/wine"

[[ -d "${SRC}/bin" ]] || {
  echo "❌ Неверная структура архива"
  exit 1
}

if [[ ! -f "${STAMP}" ]]; then
  bak="${WHISKY_WINE}.bak.$(date +%Y%m%d%H%M)"
  echo "Бэкап Wine → ${bak}"
  cp -a "${WHISKY_WINE}" "${bak}"
fi

rsync -a --delete \
  --exclude 'lib/external/' \
  "${SRC}/" "${WHISKY_WINE}/"

# Gcenx: wine64 → wine; Whisky-скрипты ожидают bin/wine64
if [[ -x "${WHISKY_WINE}/bin/wine" ]] && [[ ! -e "${WHISKY_WINE}/bin/wine64" ]]; then
  ln -sf wine "${WHISKY_WINE}/bin/wine64"
fi

bash "${GOG_DIR}/install-gptk-whisky.sh"
touch "${STAMP}"
echo "OK: Whisky Wine → staging 11.9 + GPTK D3DMetal"
"${WHISKY_WINE}/bin/wine64" --version 2>&1 | head -1
