#!/bin/sh
# Installs the AgentAlarm command and skill on the computer an AI agent runs on.
#   curl -fsSL https://agentalarm.app/install.sh | sh
# Puts `agentalarm` in ~/.local/bin and adds the skill to the agents it finds
# (OpenClaw, Claude Code, Hermes, and NanoClaw when run inside its agent container).
set -eu

BASE="${AGENTALARM_BASE:-https://agentalarm.app/agent}"
DIR="$HOME/.local/share/agentalarm"
BIN="$HOME/.local/bin"
RUN="agentalarm"
# NanoClaw wipes its container on every exit except the agent group's folder and ~/.claude, so live there.
if [ -f /app/.nanoclaw-session.json ]; then
  DIR=/workspace/agent/.agentalarm
  BIN=""
  RUN="node $DIR/agentalarm.mjs"
fi

if ! command -v node >/dev/null 2>&1 || ! node -e 'process.exit(+process.versions.node.split(".")[0] >= 20 ? 0 : 1)'; then
  echo "AgentAlarm needs Node.js 20 or later: https://nodejs.org" >&2
  exit 1
fi

mkdir -p "$DIR"
for f in agentalarm.mjs crypto.mjs SKILL.md; do
  curl -fsSL "$BASE/$f" -o "$DIR/$f.tmp" && mv "$DIR/$f.tmp" "$DIR/$f"
done
chmod 755 "$DIR/agentalarm.mjs"

# Teach the agents we can find about the skill.
for home in "$HOME/.openclaw/workspace" "$HOME/.claude" "${HERMES_HOME:-$HOME/.hermes}" "$HOME"/.hermes/profiles/*; do
  if [ -d "$home" ]; then
    mkdir -p "$home/skills/agentalarm"
    cp "$DIR/SKILL.md" "$home/skills/agentalarm/SKILL.md"
    echo "Added the AgentAlarm skill to $home/skills/agentalarm"
  fi
done

if [ -n "$BIN" ]; then
  mkdir -p "$BIN"
  ln -sf "$DIR/agentalarm.mjs" "$BIN/agentalarm"
  echo "Installed $BIN/agentalarm"
  case ":$PATH:" in
    *":$BIN:"*) ;;
    *) echo "Add $BIN to your PATH, or call $BIN/agentalarm directly." ;;
  esac
else
  echo "Installed. Run it as: $RUN"
fi
echo "Next: open AgentAlarm on your iPhone, tap Connect an agent, and run: $RUN pair <CODE>"
