#!/usr/bin/env bash
# Доп. шаги после innoextract: layout GOG, реестр, DXVK, CommonLua.
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"
GAMES_DIR="$(cd "${GOG_DIR}/.." && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"

JA3="${BOTTLE_DIR}/drive_c/GOG Games/Jagged Alliance 3"

[[ -f "${JA3}/JA3.exe" ]] || {
  echo "❌ Нет JA3 — сначала install-ja3-innoextract.sh"
  exit 1
}

# Inno Setup копирует CommonLua в корень; innoextract — только ModTools/ (Wine не видит symlink)
if [[ ! -f "${JA3}/CommonLua/Core/autorun.lua" ]]; then
  rm -rf "${JA3}/CommonLua"
  cp -R "${JA3}/ModTools/Src/CommonLua" "${JA3}/CommonLua"
  echo "  CommonLua скопирован из ModTools/Src (~9 MB)"
fi

bash "${GOG_DIR}/register-ja3-registry.sh"
bash "${GOG_DIR}/install-ja3-redist.sh" 2>/dev/null || true
if ja3_gptk_available || ja3_bottle_uses_d3dmetal; then
  bash "${GOG_DIR}/prepare-ja3-d3dmetal.sh" 2>/dev/null || bash "${GOG_DIR}/install-gptk-whisky.sh" || true
else
  if [[ -d "/Applications/Game Porting Toolkit.app" ]]; then
    bash "${GOG_DIR}/install-gptk-whisky.sh"
  else
    bash "${GOG_DIR}/install-ja3-dxmt.sh" 2>/dev/null || bash "${GOG_DIR}/install-dxvk.sh"
  fi
fi
cp -f "${GOG_DIR}/ja3-dxvk.conf" "${JA3}/dxvk.conf" 2>/dev/null || true
if ja3_gptk_available || ja3_bottle_uses_d3dmetal; then
  perl -i -pe 's/^\t\tGraphicsApi = "d3d11"/\t\tGraphicsApi = "d3d12"/' \
    "${BOTTLE_DIR}/drive_c/users/${WINE_USER:-eternal}/AppData/Roaming/Jagged Alliance 3/LocalStorage.lua" 2>/dev/null || true
else
  bash "${GOG_DIR}/force-ja3-d3d11.sh"
fi
# Intel XeSS / DLSS DLL в папке игры ломают D3D11 на MoltenVK — убрать с пути загрузки
mkdir -p "${JA3}/.disabled-upscale"
for dll in libxess.dll nvngx_dlss.dll XeFX.dll XeFX_Loader.dll dxcompiler.dll dxil.dll; do
  [[ -f "${JA3}/${dll}" ]] && mv -f "${JA3}/${dll}" "${JA3}/.disabled-upscale/${dll}"
done
bash "${GOG_DIR}/purge-steam-from-bottle.sh" >/dev/null 2>&1 || true

echo "OK: finish-ja3-layout"
