#!/usr/bin/env bash
# DXVK-macOS в GOG-bottle (для JA3).
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"
GAMES_DIR="$(cd "${GOG_DIR}/.." && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"

# install-dxvk-macos.sh привязан к HoMM config — дублируем install для GOG-bottle
DXVK_CACHE="${GAMES_DIR}/cache/dxvk-macos"
DXVK_TAR="${DXVK_CACHE}/dxvk-macOS-async.tar.gz"
DXVK_URL="https://github.com/Gcenx/DXVK-macOS/releases/download/v1.10.3-20230507-repack/dxvk-macOS-async-v1.10.3-20230507-repack.tar.gz"
DXVK_DIR="${DXVK_CACHE}/dxvk-macOS-async-v1.10.3-20230507-repack"
DXVK_X64="${DXVK_DIR}/x64"
WINE_LIB64="${WHISKY_LIBS}/Libraries/Wine/lib/wine/x86_64-windows"
SYS32="${BOTTLE_DIR}/drive_c/windows/system32"

gog_wine_check
mkdir -p "${DXVK_CACHE}"
[[ -f "${DXVK_TAR}" ]] || curl -L --fail -o "${DXVK_TAR}" "${DXVK_URL}"
[[ -f "${DXVK_X64}/d3d11.dll" ]] || tar -xzf "${DXVK_TAR}" -C "${DXVK_CACHE}"
cp -f "${WINE_LIB64}/dxgi.dll" "${SYS32}/dxgi.dll"
cp -f "${DXVK_X64}/d3d11.dll" "${SYS32}/d3d11.dll"
cp -f "${DXVK_X64}/d3d10core.dll" "${SYS32}/d3d10core.dll"
export WINEPREFIX="${BOTTLE_DIR}"
export DYLD_LIBRARY_PATH="${WINE_LIB}:${DYLD_LIBRARY_PATH:-}"
"${WINE64}" reg add 'HKEY_CURRENT_USER\Software\Wine\DllOverrides' /v d3d11 /d native,b /f >/dev/null
"${WINE64}" reg add 'HKEY_CURRENT_USER\Software\Wine\DllOverrides' /v d3d10core /d native,b /f >/dev/null
"${WINE64}" reg add 'HKEY_CURRENT_USER\Software\Wine\Direct3D' /v renderer /t REG_SZ /d vulkan /f >/dev/null 2>&1 || true
# Whisky UI: DXVK для HoMM; JA3 предпочитает D3DMetal (configure-ja3-d3dmetal.sh)
if [[ -f "${BOTTLE_DIR}/Metadata.plist" ]]; then
  /usr/libexec/PlistBuddy -c 'Set :dxvkConfig:dxvk true' "${BOTTLE_DIR}/Metadata.plist" 2>/dev/null || \
    /usr/libexec/PlistBuddy -c 'Add :dxvkConfig:dxvk bool true' "${BOTTLE_DIR}/Metadata.plist" 2>/dev/null || true
fi
echo "OK: DXVK-macOS в ${BOTTLE_NAME}"
