#!/usr/bin/env bash
# Закрепить GOG Galaxy в Whisky (Metadata.plist pins + Program Settings), как steam.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
source "${SCRIPT_DIR}/config.sh"

if ! homm_gog_exe >/dev/null; then
  echo "GOG Galaxy не установлен: bash ${SCRIPT_DIR}/start.sh gog-install"
  exit 1
fi

GOG_EXE_PATH="$(homm_gog_exe)"
METADATA="${BOTTLE_DIR}/Metadata.plist"
PROG_SETTINGS="${BOTTLE_DIR}/Program Settings/GalaxyClient.exe.plist"
# file URL как у steam (пробелы → %20)
GOG_URL="file://${BOTTLE_DIR}/drive_c/Program%20Files%20(x86)/GOG%20Galaxy/GalaxyClient.exe"

if grep -q '<string>gog</string>' "${METADATA}" 2>/dev/null; then
  echo "Pin «gog» уже есть в ${METADATA}"
else
  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 any(p.get("name") == "gog" for p in pins):
    print("pin exists")
else:
    pins.append({
        "name": "gog",
        "removable": False,
        "url": {"relative": "${GOG_URL}"},
    })
    with meta.open("wb") as f:
        plistlib.dump(data, f)
    print("pin added")
PY
  echo "OK: pin «gog» в Metadata.plist"
fi

mkdir -p "${BOTTLE_DIR}/Program Settings"
# shellcheck disable=SC2206
cef="$(echo ${GOG_GALAXY_CEF_ARGS})"
python3 <<PY
import plistlib
from pathlib import Path

ps = Path("${PROG_SETTINGS}")
data = {
    "arguments": "${cef}",
    "environment": {},
    "locale": "",
}
with ps.open("wb") as f:
    plistlib.dump(data, f)
print("OK: ${PROG_SETTINGS}")
PY

echo ""
echo "Перезапустите Whisky (Cmd+Q → open -a Whisky) — на bottle появится иконка «gog»."
echo "Запуск: клик по pin или: bash ${SCRIPT_DIR}/start.sh gog"
