#!/usr/bin/env bash
# DXMT (D3D10/11 → Metal) для JA3 без GPTK. JA3 на D3D12 всё равно нужен GPTK; скрипт + -graphicsapi d3d11.
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"
GAMES_DIR="$(cd "${GOG_DIR}/.." && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"

DXMT_CACHE="${GAMES_DIR}/cache/dxmt"
DXMT_TAR="${DXMT_CACHE}/dxmt-v0.80-builtin.tar.gz"
DXMT_URL="https://github.com/3Shain/dxmt/releases/download/v0.80/dxmt-v0.80-builtin.tar.gz"
WINE_LIB="${WHISKY_LIBS}/Libraries/Wine/lib"
WINE_LIB64="${WINE_LIB}/wine/x86_64-windows"
WINE_UNIX="${WINE_LIB}/wine/x86_64-unix"
SYS32="${BOTTLE_DIR}/drive_c/windows/system32"

gog_wine_check
mkdir -p "${DXMT_CACHE}" "${SYS32}"
[[ -f "${DXMT_TAR}" ]] || curl -L --fail -o "${DXMT_TAR}" "${DXMT_URL}"
tar -xzf "${DXMT_TAR}" -C "${DXMT_CACHE}"

# builtin layout: bin/ or root with dlls — find files
DXMT_ROOT="${DXMT_CACHE}"
for sub in dxmt-v0.80-builtin bin .; do
  [[ -f "${DXMT_CACHE}/${sub}/d3d11.dll" ]] && DXMT_ROOT="${DXMT_CACHE}/${sub}" && break
done
[[ -f "${DXMT_ROOT}/d3d11.dll" ]] || DXMT_ROOT="$(find "${DXMT_CACHE}" -name d3d11.dll -print -quit | xargs dirname)"

install_one() {
  local src="$1" dest="$2"
  [[ -f "${src}" ]] || return 0
  cp -f "${src}" "${dest}/"
}

install_one "${DXMT_ROOT}/winemetal.so" "${WINE_UNIX}"
install_one "${DXMT_ROOT}/winemetal.dll" "${WINE_LIB64}"
install_one "${DXMT_ROOT}/winemetal.dll" "${SYS32}"
install_one "${DXMT_ROOT}/d3d11.dll" "${WINE_LIB64}"
install_one "${DXMT_ROOT}/dxgi.dll" "${WINE_LIB64}"
install_one "${DXMT_ROOT}/d3d10core.dll" "${WINE_LIB64}"
# Только wine lib + system32 (не в папку игры — иначе конфликт с overrides).
install_one "${DXMT_ROOT}/d3d11.dll" "${SYS32}"
install_one "${DXMT_ROOT}/dxgi.dll" "${SYS32}"
install_one "${DXMT_ROOT}/d3d10core.dll" "${SYS32}"

export WINEPREFIX="${BOTTLE_DIR}"
export DYLD_LIBRARY_PATH="${WINE_LIB}:${DYLD_LIBRARY_PATH:-}"
"${WINE64}" reg add 'HKEY_CURRENT_USER\Software\Wine\DllOverrides' /v d3d12 /d disabled /f >/dev/null 2>&1 || true
"${WINE64}" reg delete 'HKEY_CURRENT_USER\Software\Wine\DllOverrides' /v d3d11 /f >/dev/null 2>&1 || true
"${WINE64}" reg delete 'HKEY_CURRENT_USER\Software\Wine\DllOverrides' /v d3d10core /f >/dev/null 2>&1 || true
"${WINE64}" reg delete 'HKEY_CURRENT_USER\Software\Wine\DllOverrides' /v dxgi /f >/dev/null 2>&1 || true

touch "${BOTTLE_DIR}/.ja3_dxmt_installed"
if [[ -f "${BOTTLE_DIR}/Metadata.plist" ]]; then
  /usr/libexec/PlistBuddy -c 'Set :dxvkConfig:dxvk false' "${BOTTLE_DIR}/Metadata.plist" 2>/dev/null || true
  /usr/libexec/PlistBuddy -c 'Set :performanceConfig:forceD3D11 true' "${BOTTLE_DIR}/Metadata.plist" 2>/dev/null || true
fi
echo "OK: DXMT v0.80 в ${BOTTLE_NAME} (+ game dir)"
