#!/bin/sh
# RouteMux Agent Skills installer
#   curl -fsSL https://routemux.com/.well-known/agent-skills/install.sh | sh
#   curl -fsSL https://routemux.com/.well-known/agent-skills/install.sh | sh -s -- --agent codex
#
# Options:
#   --agent NAME   claude | codex | cursor | opencode | gemini  (repeatable)
#   --dir PATH     install into this skills directory instead      (repeatable)
#   --no-key       skip the API key step
#
# Downloads each skill from routemux.com, verifies its sha256, and unpacks it into
# the skills directory of every agent it finds (or the ones you name). Then, if
# ROUTEMUX_API_KEY is not set, it offers to verify your key and save it. Skip that if
# your agent already sends its key to RouteMux: the skills reuse that one.
set -eu

BASE="https://routemux.com/.well-known/agent-skills"
API="https://api.routemux.com"

# name file sha256 — generated from the published bundle
MANIFEST='routemux-images routemux-images-125615e2.zip 125615e2c369276e32fd826ebd083ca830dcd60b40bbb32c936c91f0bdbce380
routemux-models routemux-models-7e8c917f.zip 7e8c917fa9976506889b45611f429dd90a2df67a493cb44738cc7445505492f8
routemux-setup routemux-setup-d8ed1079.zip d8ed1079b25269674239096b622d383d8be4f23bf104864990d1585908567378
routemux-video routemux-video-9abfe241.zip 9abfe24132de1557a3e2e8a9e50b2892f4d16d0936136842dc6ea429814db1cc'

say() { printf '%s\n' "$*"; }
die() { printf 'error: %s\n' "$*" >&2; exit 1; }

AGENTS=""
DIRS=""
ASK_KEY=1
while [ $# -gt 0 ]; do
  case "$1" in
    --agent) [ $# -ge 2 ] || die "--agent needs a value"; AGENTS="$AGENTS $2"; shift 2 ;;
    --dir) [ $# -ge 2 ] || die "--dir needs a value"; DIRS="$DIRS
$2"; shift 2 ;;
    --no-key) ASK_KEY=0; shift ;;
    -h|--help) sed -n '2,14p' "$0" 2>/dev/null || true; exit 0 ;;
    *) die "unknown option: $1" ;;
  esac
done

command -v curl >/dev/null 2>&1 || die "curl is required"
if command -v unzip >/dev/null 2>&1; then UNZIP=unzip
elif command -v python3 >/dev/null 2>&1; then UNZIP=python3
else die "unzip or python3 is required"; fi

sha256_of() {
  if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1
  elif command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1
  else python3 -c 'import hashlib,sys;print(hashlib.sha256(open(sys.argv[1],"rb").read()).hexdigest())' "$1"; fi
}

agent_dir() {
  case "$1" in
    claude|claude-code) printf '%s' "$HOME/.claude/skills" ;;
    codex|agents) printf '%s' "$HOME/.agents/skills" ;;
    cursor) printf '%s' "$HOME/.cursor/skills" ;;
    opencode) printf '%s' "$HOME/.config/opencode/skills" ;;
    gemini) printf '%s' "$HOME/.gemini/skills" ;;
    *) die "unknown agent: $1 (use claude, codex, cursor, opencode or gemini)" ;;
  esac
}

agent_label() {
  case "$1" in
    claude) printf 'Claude Code' ;; codex) printf 'Codex' ;; cursor) printf 'Cursor' ;;
    opencode) printf 'OpenCode' ;; gemini) printf 'Gemini CLI' ;; *) printf '%s' "$1" ;;
  esac
}

# ── where to install ─────────────────────────────────────────────────────────
TARGETS=""
add_target() {
  case "
$TARGETS
" in *"
$1
"*) ;; *) TARGETS="$TARGETS
$1" ;; esac
}

if [ -z "$AGENTS" ] && [ -z "$DIRS" ]; then
  [ -d "$HOME/.claude" ] && AGENTS="$AGENTS claude"
  { [ -d "$HOME/.codex" ] || command -v codex >/dev/null 2>&1; } && AGENTS="$AGENTS codex"
  [ -d "$HOME/.cursor" ] && AGENTS="$AGENTS cursor"
  [ -d "$HOME/.config/opencode" ] && AGENTS="$AGENTS opencode"
  [ -d "$HOME/.gemini" ] && AGENTS="$AGENTS gemini"
  if [ -n "$AGENTS" ]; then
    FOUND=""
    for a in $AGENTS; do FOUND="$FOUND, $(agent_label "$a")"; done
    say "Found: $(printf '%s' "$FOUND" | sed 's/^, //')"
  else
    say "No known agent found; installing to the shared directory ~/.agents/skills"
    AGENTS="agents"
  fi
fi
# Validate names here, in the main shell: a die inside $(agent_dir ...) would only
# exit that subshell and leave us installing to nowhere.
for a in $AGENTS; do
  case "$a" in claude|claude-code|codex|agents|cursor|opencode|gemini) ;;
    *) die "unknown agent: $a (use claude, codex, cursor, opencode or gemini)" ;; esac
  add_target "$(agent_dir "$a")"
done
OLD_IFS=$IFS
IFS='
'
for d in $DIRS; do [ -n "$d" ] && add_target "$d"; done
IFS=$OLD_IFS
TARGETS=$(printf '%s\n' "$TARGETS" | sed '/^$/d')
[ -n "$TARGETS" ] || die "nowhere to install"

# ── download, verify, unpack ─────────────────────────────────────────────────
TMP=$(mktemp -d 2>/dev/null || mktemp -d -t routemux)
trap 'rm -rf "$TMP"' EXIT INT TERM

unpack() {
  # Refuse absolute paths and ".." before writing anything.
  if [ "$UNZIP" = unzip ]; then
    if unzip -Z1 "$1" | grep -E '(^/|(^|/)\.\.(/|$))' >/dev/null; then die "unsafe path in $1"; fi
    unzip -q "$1" -d "$2"
  else
    python3 - "$1" "$2" <<'PY'
import sys, zipfile
z = zipfile.ZipFile(sys.argv[1])
for n in z.namelist():
    if n.startswith("/") or ".." in n.split("/"):
        sys.exit("unsafe path in archive: " + n)
z.extractall(sys.argv[2])
PY
  fi
}

printf '%s\n' "$MANIFEST" | while read -r NAME FILE SUM; do
  [ -n "$NAME" ] || continue
  curl -fsSL --proto '=https' "$BASE/$FILE" -o "$TMP/$FILE" || die "download failed: $BASE/$FILE"
  GOT=$(sha256_of "$TMP/$FILE")
  [ "$GOT" = "$SUM" ] || die "checksum mismatch for $FILE (expected $SUM, got $GOT); nothing installed for it"
  mkdir -p "$TMP/$NAME"
  unpack "$TMP/$FILE" "$TMP/$NAME"
  [ -f "$TMP/$NAME/SKILL.md" ] || die "$FILE has no SKILL.md at its root"
  IFS='
'
  for T in $TARGETS; do
    [ -n "$T" ] || continue
    mkdir -p "$T"
    rm -rf "$T/$NAME"
    cp -R "$TMP/$NAME" "$T/$NAME"
    chmod +x "$T/$NAME"/scripts/*.sh "$T/$NAME"/scripts/lib/*.sh 2>/dev/null || true
  done
  IFS=$OLD_IFS
  say "  ok  $NAME  (sha256 verified)"
done

say "Installed to:"
printf '%s\n' "$TARGETS" | sed 's/^/  /'

# ── API key ──────────────────────────────────────────────────────────────────
KEY_STATE=missing
if [ -n "$(printenv ROUTEMUX_API_KEY 2>/dev/null || true)" ]; then
  KEY_STATE=present
elif [ "$ASK_KEY" = 1 ] && (exec </dev/tty) 2>/dev/null; then
  say ""
  say "Your RouteMux API key (create one at https://routemux.com/console/keys)"
  say "Already using RouteMux in Claude Code, Codex, Qwen Code or Gemini CLI? The skills"
  say "reuse that key, so you can press Enter to skip."
  TRIES=0
  while [ $TRIES -lt 3 ]; do
    TRIES=$((TRIES + 1))
    printf 'Paste it here, input is hidden (press Enter to skip): ' >/dev/tty
    stty -echo </dev/tty 2>/dev/null || true
    IFS= read -r KEY </dev/tty || KEY=""
    stty echo </dev/tty 2>/dev/null || true
    printf '\n' >/dev/tty
    [ -n "$KEY" ] || break
    case "$KEY" in *[!A-Za-z0-9_.-]*) say "That does not look like a key (unexpected characters). Try again."; KEY=""; continue ;; esac
    CODE=$(curl -s -o /dev/null -w '%{http_code}' -m 20 "$API/v1/models" -H "Authorization: Bearer $KEY" || printf '000')
    if [ "$CODE" = 200 ]; then say "Key verified."; KEY_STATE=verified; break; fi
    if [ "$CODE" = 401 ] || [ "$CODE" = 403 ]; then say "RouteMux rejected that key. Try again."; KEY=""; continue; fi
    say "Could not verify the key right now (HTTP $CODE)."; KEY_STATE=unverified; break
  done

  if [ -n "$KEY" ]; then
    # SHELL can be unset (set -u would abort on a bare $SHELL); read it via printenv.
    case "$(basename "$(printenv SHELL 2>/dev/null || printf sh)")" in
      zsh) RC="$HOME/.zshrc"; LINE="export ROUTEMUX_API_KEY='$KEY'" ;;
      bash) if [ "$(uname -s)" = Darwin ]; then RC="$HOME/.bash_profile"; else RC="$HOME/.bashrc"; fi; LINE="export ROUTEMUX_API_KEY='$KEY'" ;;
      fish) RC="$HOME/.config/fish/config.fish"; LINE="set -gx ROUTEMUX_API_KEY '$KEY'" ;;
      *) RC="$HOME/.profile"; LINE="export ROUTEMUX_API_KEY='$KEY'" ;;
    esac
    SHOW_RC=$(printf '%s' "$RC" | sed "s|^$HOME|~|")
    REPLACE=0
    if [ -f "$RC" ] && grep -q 'ROUTEMUX_API_KEY' "$RC"; then
      printf '%s already sets ROUTEMUX_API_KEY. Replace it? [y/N] ' "$SHOW_RC" >/dev/tty
      read -r ANS </dev/tty || ANS=""
      case "$ANS" in [yY]*) REPLACE=1 ;; *) KEY="" ;; esac
    else
      printf 'Save it to %s so new terminals have it? It is stored there in plain text. [Y/n] ' "$SHOW_RC" >/dev/tty
      read -r ANS </dev/tty || ANS=""
      case "$ANS" in [nN]*) KEY="" ;; esac
    fi
    if [ -n "$KEY" ]; then
      mkdir -p "$(dirname "$RC")"
      if [ "$REPLACE" = 1 ]; then
        grep -v 'ROUTEMUX_API_KEY' "$RC" > "$TMP/rc" || true
        cat "$TMP/rc" > "$RC"
      fi
      printf '\n# RouteMux Agent Skills\n%s\n' "$LINE" >> "$RC"
      say "Saved to $SHOW_RC. Open a new terminal (or run: source $SHOW_RC) before starting your agent."
      KEY_STATE=saved
    else
      say "Not saved. Set it per session with: export ROUTEMUX_API_KEY='sk-...'"
    fi
  fi
fi

# ── next steps ───────────────────────────────────────────────────────────────
say ""
if [ "$KEY_STATE" = missing ]; then
  say "If your agent already uses RouteMux, the skills use that key. Otherwise set one:"
  say "  export ROUTEMUX_API_KEY='sk-...'   (create it at https://routemux.com/console/keys)"
fi
say "Next:"
say "  Restart your agent, then ask in plain words, for example:"
say "    Draw a minimalist coffee shop logo and save it to ./logo.png"
say "  Claude Code: /routemux-images    Codex: \$routemux-images"
say "  Agents started from the Dock do not read your shell profile:"
say "  https://routemux.com/docs/integrations/agent-skills/troubleshooting"
