#!/usr/bin/env bash
# Bottle создан в com.isaacmarovitz.Whisky — franke Whisky 3 его не видит → нет окна.
# Перенос bottle + Libraries symlink + whisky add (один раз).
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
source "${SCRIPT_DIR}/config.sh"

ISAAC_BOTTLE="${HOME}/Library/Containers/com.isaacmarovitz.Whisky/Bottles/${BOTTLE_ID}"
FRANKE_BOTTLE="${HOME}/Library/Containers/com.franke.Whisky/Bottles/${BOTTLE_ID}"
FRANKE_LIBS="${HOME}/Library/Application Support/com.franke.Whisky/Libraries"
ISAAC_LIBS="${HOME}/Library/Application Support/com.isaacmarovitz.Whisky/Libraries"

echo "=== Миграция bottle → franke Whisky 3 ==="

if [[ ! -d "${ISAAC_BOTTLE}/drive_c" && -d "${FRANKE_BOTTLE}/drive_c" ]]; then
  echo "Bottle уже в franke: ${FRANKE_BOTTLE}"
elif [[ -d "${ISAAC_BOTTLE}/drive_c" ]]; then
  mkdir -p "${HOME}/Library/Containers/com.franke.Whisky/Bottles"
  if [[ -e "${FRANKE_BOTTLE}" ]]; then
    echo "Удаляю битую ссылку/папку: ${FRANKE_BOTTLE}"
    rm -rf "${FRANKE_BOTTLE}"
  fi
  echo "Перенос ~11 GB (1–3 мин на SSD)…"
  mv "${ISAAC_BOTTLE}" "${FRANKE_BOTTLE}"
  echo "OK: ${FRANKE_BOTTLE}"
else
  echo "❌ Не найден bottle: ${ISAAC_BOTTLE}"
  exit 1
fi

if [[ ! -x "${FRANKE_LIBS}/Wine/bin/wine64" ]]; then
  echo "WhiskyWine в franke Libraries нет — symlink на isaacmarovitz…"
  rm -rf "${FRANKE_LIBS}"
  ln -s "${ISAAC_LIBS}" "${FRANKE_LIBS}"
fi

if command -v whisky >/dev/null 2>&1; then
  if ! whisky list 2>/dev/null | grep -q "${BOTTLE_NAME}"; then
    whisky add "${FRANKE_BOTTLE}" || echo "⚠️  whisky add вручную: Whisky → Add → ${FRANKE_BOTTLE}"
  fi
  echo "OK. BottleVM.plist обновлён для Whisky.app."
fi

# Whisky.app читает BottleVM.plist
BOTTLE_VM="${HOME}/Library/Containers/com.franke.Whisky/BottleVM.plist"
if [[ -f "${BOTTLE_VM}" ]] && ! grep -q "${BOTTLE_ID}" "${BOTTLE_VM}" 2>/dev/null; then
  echo "Добавьте bottle в Whisky вручную: Whisky → + → Add existing →"
  echo "  ${FRANKE_BOTTLE}"
fi
