#!/usr/bin/env bash
# Gcenx/DXVK-macOS — patched DX11 for Apple Silicon + MoltenVK (Whisky credits this fork).
# Vanilla DXVK 2.x and «D3DMetal» без Apple GPTK на зеркале frankea Libraries не поднимают DX11.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
source "${SCRIPT_DIR}/config.sh"

DXVK_CACHE="${GAMES_CACHE_DIR}/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"

cmd_wine_check() {
  if [[ ! -x "${WINE64}" ]]; then
    echo "Сначала: bash ${SCRIPT_DIR}/install-whiskywine-manual.sh"
    exit 1
  fi
}

cmd_download() {
  mkdir -p "${DXVK_CACHE}"
  if [[ ! -f "${DXVK_TAR}" ]]; then
    echo "==> Скачивание DXVK-macOS (~2.7 MB)..."
    curl -L -o "${DXVK_TAR}" "${DXVK_URL}"
  fi
  tar -xzf "${DXVK_TAR}" -C "${DXVK_CACHE}"
}

cmd_install() {
  if [[ ! -f "${DXVK_X64}/d3d11.dll" ]]; then
    cmd_download
  fi
  if [[ ! -d "${SYS32}" ]]; then
    echo "Нет Wine prefix (drive_c). Откройте bottle в Whisky один раз."
    exit 1
  fi
  echo "==> Копирование d3d11/d3d10core в system32, dxgi — wine builtin..."
  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
  echo "OK: DXVK-macOS v1.10.3-async в bottle ${BOTTLE_NAME}"
}

cmd_wine_check
cmd_install
