#!/usr/bin/env bash
# skill-install.sh — install a single skill into sharekit's public skills/ folder
# and optionally register it with the local hermes skills library so the running
# hermes agent can use it immediately.
#
# Usage:
#   ./skill-install.sh /path/to/SKILL.md                 # install into sharekit only
#   ./skill-install.sh /path/to/SKILL.md --register     # also install into hermes
#   ./skill-install.sh --bundle /path/to/skills-dir/    # install many skills
#
# Side effects:
#   - copies skill file(s) to /home/hermes/files/skills/...
#   - (with --register) copies to /root/.hermes/skills/<slug>/SKILL.md
#   - prints the public URL on https://files.spannerjun.top

set -euo pipefail

FILES_ROOT="/home/hermes/files"
HERMES_SKILLS="/root/.hermes/skills"
SHAREKIT_FILES="https://files.spannerjun.top/raw?path=skills"

usage() {
  cat <<EOF
$0 <SKILL.md> [--register]
$0 --bundle <skills-dir> [--register]

Options:
  --register   also install into hermes /root/.hermes/skills/<slug>/
  --bundle     treat all *.md files in given dir as skills to install
EOF
}

slugify() {
  # Strip .md, lowercase, replace [^a-z0-9.-]+ with -, trim leading/trailing -
  local name=$(basename "$1" .md)
  # drop a trailing "-skill" suffix (case-insensitive), common for SKILL.md files
  echo "$name" | tr "[:upper:]" "[:lower:]" | sed "s/-skill$//; s/[^a-z0-9.]/-/g; s/^-\+/-/; s/-$//"
}

install_one() {
  local src="$1"
  local slug=$(slugify "$src")
  local dest="$FILES_ROOT/skills/$slug.md"

  if [ -f "$dest" ] && cmp -s "$src" "$dest"; then
    echo "[skip] $slug unchanged"
  else
    cp "$src" "$dest"
    chown hermes:hermes "$dest"
    echo "[put] $src -> $dest"
  fi

  echo "    public url: $SHAREKIT_FILES/$slug.md"

  if [ "${REGISTER:-0}" = "1" ]; then
    local hdest="$HERMES_SKILLS/$slug/SKILL.md"
    mkdir -p "$HERMES_SKILLS/$slug"
    cp "$src" "$hdest"
    echo "[register] $src -> $hdest"
  fi
}

install_bundle() {
  local dir="$1"
  local count=0
  for f in "$dir"/*.md; do
    [ -f "$f" ] || continue
    install_one "$f"
    count=$((count+1))
  done
  echo "=> installed $count skill(s) from $dir"
}

main() {
  local target=""
  REGISTER=0

  if [ $# -eq 0 ]; then usage; exit 1; fi

  if [ "$1" = "--bundle" ]; then
    shift
    [ $# -ge 1 ] || { usage; exit 1; }
    target="$1"
    shift
    while [ $# -gt 0 ]; do
      case "$1" in
        --register) REGISTER=1 ;;
        *) usage; exit 1 ;;
      esac
      shift
    done
    [ -d "$target" ] || { echo "no such dir: $target" >&2; exit 1; }
    install_bundle "$target"
  else
    target="$1"
    shift
    while [ $# -gt 0 ]; do
      case "$1" in
        --register) REGISTER=1 ;;
        *) usage; exit 1 ;;
      esac
      shift
    done
    [ -f "$target" ] || { echo "no such file: $target" >&2; exit 1; }
    install_one "$target"
  fi
}

main "$@"
