#!/usr/bin/env bash
# Installs (or updates) the agents-bucket agent skill: SKILL.md + scripts/ab.sh.
#   curl -fsSL https://bucket.sky168.info/skill | bash
#   curl -fsSL https://bucket.sky168.info/skill | bash -s -- --dir ~/.agents/skills   # another skills folder
# Default folder: ~/.claude/skills (Claude Code), plus ~/.agents/skills if that folder exists.
# Needs bash + curl; the skill itself also needs jq. Writes nothing else, asks for no key.
set -euo pipefail

BASE="${AGENTS_BUCKET_URL:-https://bucket.sky168.info}"
BASE="${BASE%/}"
NAME=agents-bucket

die() { echo "install: $*" >&2; exit 1; }
command -v curl >/dev/null || die "needs curl"

roots=()
while [ $# -gt 0 ]; do
  case "$1" in
    --dir) roots+=("${2:?--dir needs a path}"); shift 2 ;;
    -h|--help) echo "usage: curl -fsSL $BASE/skill | bash [-s -- --dir <skills folder>]..."; exit 0 ;;
    *) die "unknown argument: $1 (use --dir <skills folder>)" ;;
  esac
done
if [ ${#roots[@]} -eq 0 ]; then
  roots=("$HOME/.claude/skills")
  [ -d "$HOME/.agents/skills" ] && roots+=("$HOME/.agents/skills")
fi

# Download once into a temp dir, then copy into every folder (a failed download changes nothing).
tmp=$(mktemp -d); trap 'rm -rf -- "$tmp"' EXIT
mkdir -p "$tmp/scripts"
curl -fsS -o "$tmp/SKILL.md" -- "$BASE/skills/$NAME/SKILL.md" || die "download failed: $BASE/skills/$NAME/SKILL.md"
curl -fsS -o "$tmp/scripts/ab.sh" -- "$BASE/skills/$NAME/scripts/ab.sh" || die "download failed: $BASE/skills/$NAME/scripts/ab.sh"
head -n 1 "$tmp/SKILL.md" | grep -qx -- '---' || die "unexpected response from $BASE (is this an Agents bucket server?)"

for root in "${roots[@]}"; do
  d="$root/$NAME"
  mkdir -p -- "$d/scripts"
  cp -- "$tmp/SKILL.md" "$d/SKILL.md"
  cp -- "$tmp/scripts/ab.sh" "$d/scripts/ab.sh"
  chmod 755 "$d/scripts/ab.sh" 2>/dev/null || true
  echo "installed: $d"
done

command -v jq >/dev/null || echo "note: the skill needs jq — install it (apt install jq / brew install jq)" >&2
echo "server: $BASE"
echo "next: bash \"${roots[0]}/$NAME/scripts/ab.sh\" status   (no key yet? the skill registers one; a person approves)"
