#!/usr/bin/env bash
# CrossOver bottle JA3-GOG: D3D12 через D3DMetal (единственный подтверждённый путь на M1 Pro).
# Whisky/Gcenx Wine не содержит D3DMetal hooks (см. Gcenx/macOS_Wine_builds#97).
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"

CX_APP="/Applications/CrossOver.app"
CX="${CX_APP}/Contents/SharedSupport/CrossOver"
CX_BOTTLE="JA3-GOG"
CX_DIR="${HOME}/Library/Application Support/CrossOver/Bottles/${CX_BOTTLE}"
JA3_SRC="${BOTTLE_DIR}/drive_c/GOG Games/Jagged Alliance 3"
JA3_DEST="${CX_DIR}/drive_c/GOG Games/Jagged Alliance 3"

[[ -d "${CX_APP}" ]] || {
  echo "❌ Нет CrossOver.app"
  echo "   brew install --cask crossover"
  exit 1
}
[[ -f "${JA3_SRC}/JA3.exe" ]] || {
  echo "❌ Нет JA3 в ${BOTTLE_NAME} — install-ja3-innoextract.sh"
  exit 1
}

bash "${GOG_DIR}/finish-ja3-layout.sh" >/dev/null 2>&1 || true

if [[ ! -f "${CX_DIR}/system.reg" ]]; then
  echo "Создание CrossOver bottle ${CX_BOTTLE} (win10_64)…"
  "${CX}/bin/cxbottle" --create --bottle "${CX_BOTTLE}" --description "Jagged Alliance 3 GOG" --template win10_64
fi

CONF="${CX_DIR}/cxbottle.conf"
touch "${CONF}"
sed -i '' '/^"WINED3DMETAL"/d;/^"WINEDXVK"/d' "${CONF}" 2>/dev/null || true
{
  echo '"WINED3DMETAL" = "1"'
  echo '"WINEDXVK" = "0"'
} >> "${CONF}"

mkdir -p "${CX_DIR}/drive_c/GOG Games"
if [[ -L "${JA3_DEST}" ]] || [[ ! -d "${JA3_DEST}" ]]; then
  rm -f "${JA3_DEST}"
  echo "Клон игры в CrossOver bottle (APFS clonefile, ~0 доп. места)…"
  cp -cR "${JA3_SRC}" "${JA3_DEST}"
elif [[ ! -f "${JA3_DEST}/CommonLua/Core/autorun.lua" ]]; then
  echo "Обновление CommonLua в CrossOver bottle…"
  rm -rf "${JA3_DEST}/CommonLua"
  cp -R "${JA3_SRC}/CommonLua" "${JA3_DEST}/CommonLua"
fi

LS="${CX_DIR}/drive_c/users/crossover/AppData/Roaming/Jagged Alliance 3"
mkdir -p "${LS}"
if [[ ! -f "${LS}/LocalStorage.lua" ]]; then
  cat >"${LS}/LocalStorage.lua" <<'EOF'
return {
	Options = {
		GraphicsApi = "d3d12",
		VideoPreset = "Low",
	},
}
EOF
fi

export WINEPREFIX="${CX_DIR}"
"${CX}/bin/wine" --bottle "${CX_BOTTLE}" reg add 'HKLM\Software\WOW6432Node\GOG.com\Games\1556263729' /v gameName /t REG_SZ /d 'Jagged Alliance 3' /f >/dev/null 2>&1 || true
"${CX}/bin/wine" --bottle "${CX_BOTTLE}" reg add 'HKLM\Software\WOW6432Node\GOG.com\Games\1556263729' /v exe /t REG_SZ /d 'JA3.exe' /f >/dev/null 2>&1 || true
"${CX}/bin/wine" --bottle "${CX_BOTTLE}" reg add 'HKLM\Software\WOW6432Node\GOG.com\Games\1556263729' /v path /t REG_SZ /d 'C:\GOG Games\Jagged Alliance 3\' /f >/dev/null 2>&1 || true

echo "OK: CrossOver ${CX_BOTTLE} + D3DMetal"
bash "${GOG_DIR}/fix-ja3-crossover-mouse.sh"
echo "    Запуск: bash ${GOG_DIR}/run-ja3-crossover.sh"
