#!/usr/bin/env bash
# adom-desktop installer — runs in the Adom container via `adom-wiki pkg install`.
#
# Bundled-artifact model (v1.8.147+): the Linux CLI companion + the Claude skill
# bundle ship INSIDE this package's tarball (dist/linux/, skills/). We SYMLINK
# them onto PATH / into ~/.claude/skills. Self-contained since v1.9.116: no
# external helper CLI is required (the pre-1.9.116 script hard-required the
# retired `adompkg` tool, so `adom-wiki pkg install` failed and rolled back on
# any container without it — wiki discussion #117). No download, no
# version.json dependency: the binary is right here, SHA-fixed by the published
# tarball.
#
# What it does NOT do: install the Windows/macOS GUI. That runs on the user's
# laptop (the signed Windows installer is a wiki release download; AD
# auto-updates itself). The skills tell Claude how to get the GUI onto the
# laptop.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
cd "$HERE"

# ln -sfn with a copy fallback (filesystems/sandboxes that refuse symlinks).
link_or_copy() { # <target> <linkpath>
  local target="$1" linkpath="$2"
  mkdir -p "$(dirname "$linkpath")"
  if ln -sfn "$target" "$linkpath" 2>/dev/null; then
    return 0
  fi
  rm -rf "$linkpath" 2>/dev/null || true
  cp -r "$target" "$linkpath"
}

OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
case "$OS" in
  linux)
    CLI="$HERE/dist/linux/adom-desktop"
    if [ ! -f "$CLI" ]; then
      echo "[adom-desktop] FATAL: bundled Linux CLI missing ($CLI). Package was published without staging." >&2
      exit 1
    fi
    chmod +x "$CLI"
    link_or_copy "$CLI" "$HOME/.local/bin/adom-desktop"
    case ":$PATH:" in
      *":$HOME/.local/bin:"*) ;;
      *) echo "[adom-desktop] NOTE: $HOME/.local/bin is not on PATH — add it to your shell rc." ;;
    esac
    echo "[adom-desktop] CLI -> $("$HOME/.local/bin/adom-desktop" --version 2>/dev/null || echo installed)"
    ;;
  *mingw*|*msys*|*cygwin*)
    echo "[adom-desktop] On Windows, install the GUI from https://wiki.adom.inc/adom/adom-desktop (Download box). It bundles adom-desktop-cli.exe."
    ;;
  darwin)
    echo "[adom-desktop] macOS GUI not bundled yet — see https://wiki.adom.inc/adom/adom-desktop"
    ;;
  *)
    echo "[adom-desktop] unsupported OS: $OS" >&2
    exit 1
    ;;
esac

# Claude skill bundle — symlink each skills/<slug>/ into ~/.claude/skills/<slug>.
# Best-effort per skill: one bad slug must not roll back the whole install.
if [ -d "$HERE/skills" ]; then
  linked=0
  for d in "$HERE"/skills/*/; do
    [ -f "$d/SKILL.md" ] || continue
    slug="$(basename "$d")"
    if link_or_copy "${d%/}" "$HOME/.claude/skills/$slug"; then
      linked=$((linked + 1))
    else
      echo "[adom-desktop] WARN: could not link skill $slug (continuing)" >&2
    fi
  done
  echo "[adom-desktop] linked $linked skill(s) into ~/.claude/skills/"
fi

echo "[adom-desktop] done. Try: adom-desktop ping   (needs the Adom Desktop GUI running on the user's laptop)"