#!/usr/bin/env bash
# Pin GOG Galaxy в Whisky для bottle GOG-Install (как start.sh gog в HoMM).
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"

GOG_EXE="${BOTTLE_DIR}/drive_c/Program Files (x86)/GOG Galaxy/GalaxyClient.exe"
[[ -f "${GOG_EXE}" ]] || { echo "Нет GalaxyClient — install-galaxy-extract.sh"; exit 1; }

METADATA="${BOTTLE_DIR}/Metadata.plist"
PROG_SETTINGS="${BOTTLE_DIR}/Program Settings/GalaxyClient.exe.plist"
GOG_URL="file://${BOTTLE_DIR}/drive_c/Program%20Files%20(x86)/GOG%20Galaxy/GalaxyClient.exe"
CEF="$(gog_galaxy_cef_args_array | tr '\n' ' ')"

python3 <<PY
import plistlib
from pathlib import Path

meta = Path("${METADATA}")
with meta.open("rb") as f:
    data = plistlib.load(f)
pins = data.setdefault("info", {}).setdefault("pins", [])
if not any(p.get("name") == "gog-galaxy" for p in pins):
    pins.append({
        "name": "gog-galaxy",
        "removable": False,
        "url": {"relative": "${GOG_URL}"},
    })
    with meta.open("wb") as f:
        plistlib.dump(data, f)
    print("pin gog-galaxy added")
else:
    print("pin exists")

ps = Path("${PROG_SETTINGS}")
ps.parent.mkdir(parents=True, exist_ok=True)
with ps.open("wb") as f:
    plistlib.dump({"arguments": "${CEF}", "environment": {}, "locale": ""}, f)
print("OK:", ps)
PY

echo ""
echo "Whisky → ${BOTTLE_NAME} → pin «gog-galaxy» → Run"
echo "Или: bash ${GOG_DIR}/launch-galaxy.sh"
