#!/usr/bin/env bash
# Install or update the PCBFlux (Cogniviz.ai) agent skills for Claude Code from https://pcbflux.com.
#   curl -fsSL https://pcbflux.com/skills/install.sh | bash
#   ... | bash -s -- --dir <skills dir>      (default: ~/.claude/skills; a project: <repo>/.claude/skills)
#   ... | bash -s -- --only eda-portal        (one skill)
#   ... | bash -s -- --check                  (say what would change, write nothing)
# Run it again whenever you like: only files that changed are written. Each skill goes to <dir>/<name>/ (SKILL.md and its files).
# Needs curl and python3. Reads only from https://pcbflux.com; writes only under <dir>.
set -euo pipefail
ORIGIN="https://pcbflux.com"
DIR="${HOME}/.claude/skills"; ONLY=""; CHECK=0
while [ $# -gt 0 ]; do
  case "$1" in
    --dir) DIR="$2"; shift 2 ;;
    --only) ONLY="$2"; shift 2 ;;
    --check) CHECK=1; shift ;;
    -h|--help) sed -n '2,8p' "$0" 2>/dev/null || true; exit 0 ;;
    *) echo "Unknown option $1" >&2; exit 2 ;;
  esac
done
command -v curl >/dev/null || { echo "curl is needed" >&2; exit 1; }
command -v python3 >/dev/null || { echo "python3 is needed" >&2; exit 1; }
TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
curl -fsSL -A "eda-skills-installer/1" "$ORIGIN/skills/index.json" -o "$TMP/index.json"
mkdir -p "$DIR"
python3 - "$TMP/index.json" "$DIR" "$ONLY" "$CHECK" "$TMP" <<'PY'
import hashlib, json, os, re, sys, urllib.request
index, base, only, check, tmp = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4] == "1", sys.argv[5]
data = json.load(open(index))
base = os.path.realpath(os.path.expanduser(base))
changed = same = 0
for s in data["skills"]:
    name = s["name"]
    if only and name != only: continue
    if not re.fullmatch(r"[a-z0-9-]{1,40}", name): sys.exit(f"bad skill name {name!r}")
    for f in s["files"]:
        rel = f["path"]
        if not re.fullmatch(r"[A-Za-z0-9_.-]+(/[A-Za-z0-9_.-]+)*", rel) or ".." in rel.split("/"): sys.exit(f"bad path {rel!r}")
        dest = os.path.realpath(os.path.join(base, name, rel))
        if not dest.startswith(os.path.join(base, name) + os.sep): sys.exit(f"path leaves the skill folder: {rel!r}")
        have = hashlib.sha256(open(dest, "rb").read()).hexdigest() if os.path.exists(dest) else None
        if have == f["sha256"]: same += 1; continue
        if check: print(("update " if have else "new    ") + f"{name}/{rel}"); changed += 1; continue
        req = urllib.request.Request(f["url"], headers={"user-agent": "eda-skills-installer/1"})
        body = urllib.request.urlopen(req, timeout=60).read()
        if hashlib.sha256(body).hexdigest() != f["sha256"]: sys.exit(f"{name}/{rel} changed while installing: run the installer again")
        os.makedirs(os.path.dirname(dest), exist_ok=True)
        part = dest + ".part"
        open(part, "wb").write(body); os.replace(part, dest)
        print(("updated " if have else "added   ") + f"{name}/{rel}"); changed += 1
    if not check and (not only or name == only):
        open(os.path.join(base, name, ".eda-skill.json"), "w").write(json.dumps({"origin": data.get("origin"), "version": data["version"], "skill": name}) + "\n")
verb = "would change" if check else "changed"
print(f"skills version {data['version']}: {changed} file(s) {verb}, {same} already current, in {base}")
if not check and changed: print("Start a new Claude Code session (or run /reload-skills if your version has it) to pick them up.")
PY
