#!/usr/bin/env bash
# Apple D3DMetal (GPTK) в Whisky Libraries — только framework + unix-мост.
# НЕ ditto всего GPTK lib (перезапишет wine64 на 7.7 и сломает bottle).
# Канон: https://github.com/Whisky-App/Whisky/issues/124
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"

GPTK_APP="${GPTK_APP:-/Applications/Game Porting Toolkit.app}"
GPTK_WINE="${GPTK_APP}/Contents/Resources/wine"
WHISKY_WINE="${WHISKY_LIBS}/Libraries/Wine"
EXT="${WHISKY_WINE}/lib/external"
WINE_UNIX="${WHISKY_WINE}/lib/wine/x86_64-unix"

[[ -d "${GPTK_WINE}/lib/external/D3DMetal.framework" ]] || {
  echo "❌ Нет Game Porting Toolkit.app"
  echo "   brew install --cask gcenx/wine/game-porting-toolkit"
  exit 1
}

mkdir -p "${EXT}"
ditto "${GPTK_WINE}/lib/external/D3DMetal.framework" "${EXT}/D3DMetal.framework"
cp -f "${GPTK_WINE}/lib/external/libd3dshared.dylib" "${EXT}/libd3dshared.dylib"

# @rpath @loader_path — копия в корень lib/ (fixmywhisky)
cp -Rf "${EXT}/D3DMetal.framework" "${WHISKY_WINE}/lib/D3DMetal.framework"
cp -f "${EXT}/libd3dshared.dylib" "${WHISKY_WINE}/lib/libd3dshared.dylib"

fix_d3dmetal_fw() {
  local fw="$1"
  [[ -d "${fw}/Versions" ]] || return 0
  rm -f "${fw}/D3DMetal" "${fw}/Resources" 2>/dev/null || true
  ln -sf Versions/Current/D3DMetal "${fw}/D3DMetal"
  ln -sf Versions/Current/Resources "${fw}/Resources"
  chmod +x "${fw}/Versions/Current/D3DMetal" 2>/dev/null || true
  xattr -d com.apple.quarantine "${fw}" 2>/dev/null || true
}
fix_d3dmetal_fw "${EXT}/D3DMetal.framework"
fix_d3dmetal_fw "${WHISKY_WINE}/lib/D3DMetal.framework"
chmod +x "${EXT}/libd3dshared.dylib" "${WHISKY_WINE}/lib/libd3dshared.dylib" 2>/dev/null || true
xattr -d com.apple.quarantine "${EXT}/libd3dshared.dylib" 2>/dev/null || true

# Мост D3DMetal: unix .so → libd3dshared. PE d3d12/dxgi — от Gcenx Wine 11.x (не GPTK 7.7).
mkdir -p "${WINE_UNIX}"
ln -sf ../../external/libd3dshared.dylib "${WINE_UNIX}/d3d12.so"
ln -sf ../../external/libd3dshared.dylib "${WINE_UNIX}/dxgi.so"

touch "${WHISKY_LIBS}/Libraries/.gptk_installed"
echo "OK: GPTK D3DMetal + d3d12/dxgi bridge → ${WHISKY_WINE}"
echo "    Запуск: bash ${GOG_DIR}/prepare-ja3-d3dmetal.sh && bash ${GOG_DIR}/run-ja3.sh"
