#!/bin/sh
# kungfu-bootstrap — install one skill from a Skillz library page, safely, any number of times.
#
# Default: the kungfu-download skill from https://iknowkungfu.club, which can then install
# everything else. Never pipe this into a shell: download it, read it, check its hash, then
#   sh kungfu-bootstrap.sh --dry-run && sh kungfu-bootstrap.sh
#
# What it guarantees
#   - nothing is written until every file is downloaded, checked and hash-verified
#   - an existing copy is never merged into: it is moved to ~/.claude/skill-backups/<name>/<UTC>/
#     (outside the skills folder, so the agent never loads a backup) and the new copy renamed in
#   - running it again with nothing changed changes nothing
#
# Exit codes: 0 ok · 2 usage · 3 missing tool · 4 network · 5 invalid content
#             6 hash mismatch · 7 unsafe destination · 10 declined · 64 target not supported yet
# Source: https://iknowkungfu.club/view/dojo-plan

set -eu
umask 022

SOURCE="https://iknowkungfu.club"
SLUG="kungfu-download-skill"
NAME="kungfu-download"
TARGET="claude"
DRY=0; YES=0; FORCE=0; VERIFY=1; QUIET=0; MODE=install; RESTORE_STAMP=""

say()  { [ "$QUIET" = 1 ] || printf '%s\n' "$*"; }
warn() { printf 'kungfu-bootstrap: %s\n' "$*" >&2; }
die()  { code=$1; shift; warn "$*"; exit "$code"; }

usage() {
  cat <<'EOF'
usage: sh kungfu-bootstrap.sh [options]
  --dry-run        check everything and say what would happen; write nothing
  --yes            do not ask before replacing an existing copy
  --force          replace even a symlink at the destination
  --no-verify      allow a skill that has no MANIFEST (hashes are not checked)
  --source URL     library to install from (default https://iknowkungfu.club)
  --slug SLUG      skill page slug (default kungfu-download-skill)
  --name NAME      expected skill name (default kungfu-download)
  --target claude  agent to install for (only claude so far)
  --quiet          print errors only
  --restore [STAMP]  put back the newest backup of --name (or the one named STAMP)
  --migrate-backups  move old <name>.bak.* folders out of the skills folder
Backups: ~/.claude/skill-backups/<name>/<UTC>/ — the 3 newest are kept, plus any
younger than 30 days; older ones are removed after a successful install.
EOF
}

while [ $# -gt 0 ]; do
  case "$1" in
    --dry-run) DRY=1 ;;
    --yes) YES=1 ;;
    --force) FORCE=1 ;;
    --no-verify) VERIFY=0 ;;
    --quiet) QUIET=1 ;;
    --source) [ $# -ge 2 ] || { usage >&2; exit 2; }; SOURCE=${2%/}; shift ;;
    --slug) [ $# -ge 2 ] || { usage >&2; exit 2; }; SLUG=$2; shift ;;
    --name) [ $# -ge 2 ] || { usage >&2; exit 2; }; NAME=$2; shift ;;
    --target) [ $# -ge 2 ] || { usage >&2; exit 2; }; TARGET=$2; shift ;;
    --restore) MODE=restore; case "${2:-}" in ""|--*) ;; *) RESTORE_STAMP=$2; shift ;; esac ;;
    --migrate-backups) MODE=migrate ;;
    -h|--help) usage; exit 0 ;;
    *) usage >&2; exit 2 ;;
  esac
  shift
done

case "$TARGET" in
  claude) SKILLS="$HOME/.claude/skills"; BACKUPS="$HOME/.claude/skill-backups" ;;
  codex) die 64 "the codex target is planned but not built yet (see Dojo Plan, Phase 7)" ;;
  *) die 2 "unknown target: $TARGET" ;;
esac
PROTO='=https'
case "$SOURCE" in
  https://*) ;;
  http://localhost|http://localhost:*|http://localhost/*|http://127.0.0.1*|http://*.localhost|http://*.localhost:*|http://*.localhost/*) PROTO='=http,https' ;;
  *) die 2 "--source must be an https:// address (plain http only for localhost libraries)" ;;
esac
printf '%s' "$SLUG$NAME" | grep -q '^[A-Za-z0-9._-]*$' || die 2 "slug and name may only contain letters, digits, . _ -"

# --- tools ---------------------------------------------------------------------------
for t in curl mktemp mv awk sed sort diff grep; do
  command -v "$t" >/dev/null 2>&1 || die 3 "needs '$t' but it is not installed"
done
if command -v shasum >/dev/null 2>&1; then SHA="shasum -a 256"
elif command -v sha256sum >/dev/null 2>&1; then SHA="sha256sum"
else die 3 "needs shasum or sha256sum"; fi
sha_of() { $SHA "$1" | awk '{print $1}'; }

# --- restore and migrate (no download) -------------------------------------------
confirm() { # confirm "question" -> 0 yes, 1 no; honours --yes; no terminal means no
  [ "$YES" = 1 ] && return 0
  if ( : > /dev/tty ) 2>/dev/null; then
    printf '%s [y/N] ' "$1" > /dev/tty; read -r ans < /dev/tty || ans=""
    case "$ans" in y|Y|yes|YES) return 0 ;; esac
  fi
  return 1
}
if [ "$MODE" = restore ]; then
  B="$BACKUPS/$NAME"
  [ -d "$B" ] || die 7 "no backups of $NAME in $B"
  if [ -n "$RESTORE_STAMP" ]; then PICK="$RESTORE_STAMP"; else PICK=$(ls -1 "$B" | grep '^[0-9]' | LC_ALL=C sort | tail -1); [ -n "$PICK" ] || PICK=$(ls -1 "$B" | LC_ALL=C sort | tail -1); fi
  [ -n "$PICK" ] && [ -d "$B/$PICK" ] || die 7 "no backup $B/${PICK:-?}"
  DEST="$SKILLS/$NAME"; STAMP=$(date -u +%Y%m%dT%H%M%SZ)
  say "Plan:     restore $B/$PICK to $DEST"
  [ -e "$DEST" ] && say "          the current copy goes to $B/$STAMP"
  [ "$DRY" = 1 ] && { say "Dry run: nothing was written."; exit 0; }
  confirm "Restore $NAME from $PICK?" || { say "Declined: nothing changed."; exit 10; }
  mkdir -p "$SKILLS"
  if [ -e "$DEST" ] || [ -L "$DEST" ]; then mv "$DEST" "$B/$STAMP"; touch "$B/$STAMP"; fi
  mv "$B/$PICK" "$DEST" || die 7 "could not restore $PICK"
  say "Restored: $DEST from $PICK"; exit 0
fi
if [ "$MODE" = migrate ]; then
  found=0
  for d in "$SKILLS"/*.bak.*; do
    [ -d "$d" ] || continue
    found=1; base=$(basename "$d"); n=${base%%.bak.*}; t=${base##*.bak.}
    say "Plan:     move $d to $BACKUPS/$n/legacy-$t"
    if [ "$DRY" != 1 ] && confirm "Move $base out of the skills folder?"; then
      mkdir -p "$BACKUPS/$n"; mv "$d" "$BACKUPS/$n/legacy-$t"
    fi
  done
  [ "$found" = 1 ] || say "No old .bak folders in $SKILLS."
  exit 0
fi

prune() { # keep the 3 newest backups of $NAME, and any younger than 30 days
  B="$BACKUPS/$NAME"; [ -d "$B" ] || return 0
  ls -1 "$B" | LC_ALL=C sort -r | tail -n +4 | while IFS= read -r old; do
    if [ -n "$(find "$B/$old" -maxdepth 0 -mtime +30 2>/dev/null)" ]; then rm -rf "${B:?}/$old"; say "Pruned:    $B/$old"; fi
  done
}

STAGE=$(mktemp -d "${TMPDIR:-/tmp}/kungfu-bootstrap.XXXXXX") || die 3 "cannot create a temporary folder"
NEW=""
cleanup() { rm -rf "$STAGE"; if [ -n "$NEW" ]; then rm -rf "$NEW"; fi; true; }
trap cleanup EXIT
trap 'exit 130' INT TERM

# --- download ------------------------------------------------------------------------
# fetch URL OUT: https only, fail on HTTP errors, refuse HTML (a wiki 404 page is HTML)
fetch() {
  ctype=$(curl -fsSL --proto "$PROTO" --max-time 30 --retry 2 -o "$2" -w '%{content_type}' "$1") \
    || die 4 "could not download $1"
  case "$ctype" in text/html*) die 5 "$1 returned a web page, not a file" ;; esac
}

say "Library:  $SOURCE"
say "Skill:    $SLUG -> $SKILLS/$NAME"
fetch "$SOURCE/plugin/assets/list?assets=$SLUG" "$STAGE/list.json"
grep -q '"files"[[:space:]]*:[[:space:]]*\[' "$STAGE/list.json" || die 5 "the library did not return a file list for $SLUG"
FILES=$(tr -d '\n' < "$STAGE/list.json" | sed 's/.*"files"[[:space:]]*:[[:space:]]*\[\([^]]*\)\].*/\1/' | tr ',' '\n' | sed 's/^[[:space:]]*"//; s/"[[:space:]]*$//' | grep -v '^$' || true)
[ -n "$FILES" ] || die 5 "the page $SLUG has no files attached"
printf '%s\n' "$FILES" | grep -qx 'SKILL.md' || die 5 "the page $SLUG has no SKILL.md"

mkdir "$STAGE/skill"
for f in $FILES; do
  printf '%s' "$f" | grep -q '^[A-Za-z0-9._-]*$' || die 5 "refusing an unsafe file name: $f"
  case "$f" in .*) die 5 "refusing a hidden file: $f" ;; esac
  if [ "$f" = MANIFEST ]; then fetch "$SOURCE/assets/$SLUG/$f" "$STAGE/MANIFEST"
  else fetch "$SOURCE/assets/$SLUG/$f" "$STAGE/skill/$f"; fi
done

# --- check SKILL.md ------------------------------------------------------------------
S="$STAGE/skill/SKILL.md"
[ "$(sed -n 1p "$S")" = "---" ] || die 5 "SKILL.md does not start with a --- header"
awk 'NR>1 && /^---[[:space:]]*$/ {found=1; exit} END {exit !found}' "$S" || die 5 "SKILL.md header is not closed"
HEAD=$(awk 'NR>1 && /^---[[:space:]]*$/ {exit} NR>1 {print}' "$S")
GOT=$(printf '%s\n' "$HEAD" | sed -n 's/^name:[[:space:]]*//p' | sed 's/[[:space:]]*$//; s/^["'\'']//; s/["'\'']$//' | head -1)
[ "$GOT" = "$NAME" ] || die 5 "SKILL.md is named '$GOT', expected '$NAME'"
printf '%s\n' "$HEAD" | grep -q '^description:' || die 5 "SKILL.md has no description"
grep -qi '<html' "$S" && die 5 "SKILL.md contains HTML"

# --- verify hashes -------------------------------------------------------------------
VERSION="unversioned"
if [ -f "$STAGE/MANIFEST" ]; then
  for f in $FILES; do
    [ "$f" = MANIFEST ] && continue
    want=$(awk -v p="$f" '$3==p {print $1}' "$STAGE/MANIFEST")
    [ -n "$want" ] || die 6 "MANIFEST does not list $f"
    [ "$(sha_of "$STAGE/skill/$f")" = "$want" ] || die 6 "$f does not match its MANIFEST hash"
  done
  VERSION=$(awk 'NF>=3 {print $2; exit}' "$STAGE/MANIFEST")
  say "Verified: every file matches MANIFEST (version $VERSION)"
elif [ "$VERIFY" = 1 ]; then
  die 6 "no MANIFEST on $SLUG, so the files cannot be verified (use --no-verify to accept that)"
else
  warn "no MANIFEST: installing without hash verification"
fi

# --- compare with what is installed --------------------------------------------------
tree_hash() { # hash of every regular file (name + content), ignoring .DS_Store
  ( cd "$1" && find . -type f ! -name .DS_Store | LC_ALL=C sort | while IFS= read -r p; do
      printf '%s %s\n' "$p" "$(sha_of "$p")"; done ) | $SHA | awk '{print $1}'
}
DEST="$SKILLS/$NAME"
STATE=fresh
if [ -L "$DEST" ]; then STATE=symlink
elif [ -e "$DEST" ] && [ ! -d "$DEST" ]; then STATE=invalid
elif [ -d "$DEST" ]; then
  if [ "$(tree_hash "$DEST")" = "$(tree_hash "$STAGE/skill")" ]; then STATE=same
  elif [ -f "$DEST/SKILL.md" ] && [ "$(sed -n 1p "$DEST/SKILL.md")" = "---" ]; then STATE=different
  else STATE=invalid; fi
fi

case "$STATE" in
  same) say "Up to date: $DEST already matches. Nothing to do."; exit 0 ;;
  symlink) [ "$FORCE" = 1 ] || die 7 "$DEST is a symlink; refusing to replace it without --force" ;;
esac

STAMP=$(date -u +%Y%m%dT%H%M%SZ)
case "$STATE" in
  fresh) say "Plan:     install new copy at $DEST" ;;
  different) say "Plan:     replace the installed copy; the old one goes to $BACKUPS/$NAME/$STAMP" ;;
  invalid) say "Plan:     $DEST is not a valid skill; move it to $BACKUPS/$NAME/$STAMP and install" ;;
  symlink) say "Plan:     move the symlink to $BACKUPS/$NAME/$STAMP and install (--force)" ;;
esac

if [ "$STATE" = different ]; then
  say ""; say "Changes from the installed copy:"
  diff -ru "$DEST" "$STAGE/skill" || true
  say ""
fi

if [ "$DRY" = 1 ]; then say "Dry run: nothing was written."; exit 0; fi

if [ "$STATE" != fresh ] && [ "$YES" != 1 ]; then
  if ( : > /dev/tty ) 2>/dev/null; then
    printf 'Replace %s? [y/N] ' "$DEST" > /dev/tty
    read -r ans < /dev/tty || ans=""
    case "$ans" in y|Y|yes|YES) ;; *) say "Declined: nothing changed."; exit 10 ;; esac
  else
    die 10 "an existing copy would be replaced; re-run with --yes to allow it"
  fi
fi

# --- install: build the new copy beside the destination, then rename ------------------
mkdir -p "$SKILLS"
NEW=$(mktemp -d "$HOME/.claude/.kungfu-new.XXXXXX") || die 7 "cannot write under $HOME/.claude"
cp -R "$STAGE/skill/." "$NEW/"
chmod -R u+rwX,go+rX "$NEW"
if [ "$STATE" != fresh ]; then
  mkdir -p "$BACKUPS/$NAME"
  mv "$DEST" "$BACKUPS/$NAME/$STAMP" || die 7 "could not move the old copy aside"
  touch "$BACKUPS/$NAME/$STAMP"   # age a backup from when it was made, not last edited
fi
if ! mv "$NEW" "$DEST"; then
  if [ "$STATE" != fresh ]; then mv "$BACKUPS/$NAME/$STAMP" "$DEST"; fi
  die 7 "could not move the new copy into place; the old copy was restored"
fi
NEW=""

prune
say "Installed: $DEST ($VERSION)"
[ "$STATE" = fresh ] || say "Backup:    $BACKUPS/$NAME/$STAMP"
say "Next:      restart your agent so it loads the skill, then ask it to"
say "           \"download the Kungfu Skills collection from iknowkungfu.club\"."
