#!/usr/bin/env bash
# Создать пустой Whisky-bottle «GOG-Install» (wineboot --init), без Steam.
set -euo pipefail
GOG_SCRIPTS="$(cd "$(dirname "$0")" && pwd)"
FRANKE="${HOME}/Library/Containers/com.franke.Whisky"
WHISKY_LIBS="${HOME}/Library/Application Support/com.franke.Whisky/Libraries"
WINE64="${WHISKY_LIBS}/Wine/bin/wine64"
WINE_LIB="${WHISKY_LIBS}/Wine/lib"
NAME="${1:-GOG-Install}"

if [[ -f "${GOG_SCRIPTS}/bottle.env" ]]; then
  # shellcheck source=/dev/null
  source "${GOG_SCRIPTS}/bottle.env"
  if [[ -d "${FRANKE}/Bottles/${BOTTLE_ID}/drive_c" ]]; then
    echo "Bottle уже есть: ${BOTTLE_NAME} (${BOTTLE_ID})"
    exit 0
  fi
fi

if [[ ! -x "${WINE64}" ]]; then
  echo "Нет Wine: bash $(dirname "$GOG_SCRIPTS")/install-whiskywine-manual.sh"
  exit 1
fi

BOTTLE_ID="$(uuidgen | tr '[:upper:]' '[:lower:]')"
BOTTLE_PATH="${FRANKE}/Bottles/${BOTTLE_ID}"
mkdir -p "${BOTTLE_PATH}"

echo "Создаю префикс Wine: ${BOTTLE_PATH} (2–5 мин)…"
export WINEPREFIX="${BOTTLE_PATH}"
export DYLD_LIBRARY_PATH="${WINE_LIB}:${DYLD_LIBRARY_PATH:-}"
export WINEDEBUG=-all
"${WINE64}" wineboot --init

python3 <<PY
import plistlib
from pathlib import Path

meta = Path("${BOTTLE_PATH}") / "Metadata.plist"
data = {
    "info": {"name": "${NAME}", "pins": [], "blocklist": []},
    "displayConfig": {
        "customWidth": 1920,
        "customHeight": 1080,
        "resolutionPreset": "r1920x1080",
        "virtualDesktopEnabled": False,
    },
    "dxvkConfig": {"dxvk": False, "dxvkAsync": True, "dxvkHud": {"off": {}}},
    "graphicsConfig": {"backend": "recommended"},
    "audioConfig": {
        "audioDriver": "auto",
        "latencyPreset": "defaultPreset",
        "outputDeviceMode": "followSystem",
    },
    "cleanupConfig": {
        "clipboardPolicy": "auto",
        "clipboardThreshold": 10240,
        "closeWithProcessesPolicy": "ask",
        "killOnQuit": "inherit",
    },
    "customDLLOverrides": [],
    "fileVersion": {"major": 1, "minor": 0, "patch": 0, "build": "", "preRelease": ""},
}
with meta.open("wb") as f:
    plistlib.dump(data, f)
print("Metadata.plist OK")
PY

BOTTLE_VM="${FRANKE}/BottleVM.plist"
python3 <<PY
import plistlib
from pathlib import Path

vm = Path("${BOTTLE_VM}")
url = "file://${BOTTLE_PATH}"
if vm.exists():
    with vm.open("rb") as f:
        data = plistlib.load(f)
else:
    data = {"fileVersion": {"major": 1, "minor": 0, "patch": 0, "build": "", "preRelease": ""}, "paths": []}
paths = data.setdefault("paths", [])
if not any(p.get("relative", "").endswith("${BOTTLE_ID}") for p in paths):
    paths.append({"relative": url})
with vm.open("wb") as f:
    plistlib.dump(data, f)
print("BottleVM.plist OK")
PY

if command -v whisky >/dev/null 2>&1; then
  whisky add "${BOTTLE_PATH}" 2>/dev/null || true
fi

cat >"${GOG_SCRIPTS}/bottle.env" <<EOF
BOTTLE_ID=${BOTTLE_ID}
BOTTLE_NAME=${NAME}
EOF

echo ""
echo "OK: ${NAME}"
echo "  UUID: ${BOTTLE_ID}"
echo "  Path: ${BOTTLE_PATH}"
echo "Дальше: bash ${GOG_SCRIPTS}/setup-bottle.sh"
