#!/usr/bin/env bash
# vertu-onboard skill installer (POSIX bash)
# Usage:
#   curl -fsSL https://unpkg.com/vertu-cli@latest/scripts/install-onboard-skill.sh | bash
#
# Behavior:
#   - Downloads vertu-onboard/SKILL.md from the npm package on unpkg (override via VERTU_ONBOARD_RAW)
#   - Detects which AI agent root directories already exist under $HOME and writes
#     <agent>/skills/vertu-onboard/SKILL.md into each
#   - Falls back to ~/.cursor/skills/vertu-onboard/ when no agent root is detected
#   - Idempotent: re-running just rewrites the SKILL.md
#
# After running, tell your AI agent (Cursor / Claude Code / Trae / ...) something like:
#   "Use the vertu-onboard skill to install vertu-cli on this machine."

set -euo pipefail

RAW="${VERTU_ONBOARD_RAW:-https://unpkg.com/vertu-cli@latest/skills/vertu-onboard/SKILL.md}"

echo "[vertu-onboard] fetching SKILL.md from $RAW"
TMP="$(mktemp)"
trap 'rm -f "$TMP"' EXIT
if ! curl -fsSL --max-time 30 "$RAW" -o "$TMP"; then
    echo "Failed to fetch SKILL.md from $RAW" >&2
    exit 1
fi

# Pairs of "<agent_id>:<root_dir_under_home>" — root_dir is also the marker that
# proves the user actually uses that agent. We write into <home>/<root>/skills/vertu-onboard/.
AGENTS=(
    "cursor:.cursor"
    "claude:.claude"
    "trae:.trae"
    "trae-cn:.trae-cn"
    "openclaw:.openclaw"
    "hermes:.hermes"
)

HOME_DIR="${HOME:?HOME not set}"
written=()

for entry in "${AGENTS[@]}"; do
    id="${entry%%:*}"
    root="${entry##*:}"
    marker="$HOME_DIR/$root"
    [ -d "$marker" ] || continue
    dest_dir="$marker/skills/vertu-onboard"
    mkdir -p "$dest_dir"
    cp "$TMP" "$dest_dir/SKILL.md"
    written+=("$id → $dest_dir/SKILL.md")
done

if [ "${#written[@]}" -eq 0 ]; then
    echo "[vertu-onboard] no AI agent root detected under $HOME_DIR ; falling back to Cursor."
    dest_dir="$HOME_DIR/.cursor/skills/vertu-onboard"
    mkdir -p "$dest_dir"
    cp "$TMP" "$dest_dir/SKILL.md"
    written+=("cursor (fallback) → $dest_dir/SKILL.md")
fi

echo
echo "[vertu-onboard] installed to:"
for w in "${written[@]}"; do echo "  $w"; done
echo
echo "Next: open your AI agent and say:"
echo '  "Use the vertu-onboard skill to install vertu-cli on this machine."'
