#!/usr/bin/env bash
# sign-skills.sh  -  v6.2.H
#
# Generates a SHA-256 manifest of every SKILL.md under pipeline/skills/.
# Output: pipeline/skills/.skill-manifest.json (in the authored tree  -  becomes
# part of what install.js copies, so the deployed dirs get the manifest too).
#
# The manifest is NOT a security boundary. It's a tamper-detection signal:
# install → verify → flag if anything changed under the user's ~/.claude/skills/
# between runs. Real attestation would need keys we don't ship.
#
# Usage: sign-skills.sh [--root <dir>]   # default: ./pipeline/skills
#
# Exit: 0 on success, 1 if skills root missing or sha256sum unavailable.

set -euo pipefail

ROOT_OVERRIDE=""
while [ $# -gt 0 ]; do
  case "$1" in
    --root) ROOT_OVERRIDE="$2"; shift 2 ;;
    *) shift ;;
  esac
done

REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
SKILLS_ROOT="${ROOT_OVERRIDE:-$REPO_ROOT/pipeline/skills}"
MANIFEST="$SKILLS_ROOT/.skill-manifest.json"

[ -d "$SKILLS_ROOT" ] || { echo "sign-skills: $SKILLS_ROOT not a directory" >&2; exit 1; }

hasher=""
if command -v sha256sum >/dev/null 2>&1; then
  hasher=sha256sum
elif command -v shasum >/dev/null 2>&1; then
  hasher="shasum -a 256"
else
  echo "sign-skills: need sha256sum or shasum" >&2
  exit 1
fi

command -v jq >/dev/null 2>&1 || { echo "sign-skills: jq required" >&2; exit 1; }

generated_at=$(date -u '+%Y-%m-%dT%H:%M:%SZ')

# Build entries: path (relative to skills root) + sha256
entries=$(find "$SKILLS_ROOT" -type f -name 'SKILL.md' -print0 2>/dev/null \
  | xargs -0 $hasher 2>/dev/null \
  | while read -r sum path; do
      rel="${path#"$SKILLS_ROOT"/}"
      jq -nc --arg path "$rel" --arg sha "$sum" '{path: $path, sha256: $sha}'
    done \
  | jq -s 'sort_by(.path)')

count=$(jq 'length' <<< "$entries")

jq -n --arg v "1.0.0" --arg at "$generated_at" --argjson count "$count" --argjson entries "$entries" '
  {
    schemaVersion: $v,
    generatedAt: $at,
    skillCount: $count,
    entries: $entries
  }
' > "$MANIFEST"

echo "sign-skills: wrote $MANIFEST ($count skills hashed)"
exit 0
