#!/bin/sh
# ClawBump installer
# Usage: curl -fsSL https://agent-knowhow.vercel.app/install.sh | sh -s -- <source>

set -e

SOURCE="${1:-unknown}"
CLI_URL="https://agent-knowhow.vercel.app/cli.js"
INSTALL_DIR="$HOME/.clawbump/bin"
BIN="$INSTALL_DIR/clawbump"
CONFIG_DIR="$HOME/.knowhow"
CONFIG_FILE="$CONFIG_DIR/config.json"

echo "Installing ClawBump..."

# Check Node.js
if ! command -v node >/dev/null 2>&1; then
  echo ""
  echo "✗ Node.js is required but not installed."
  echo "  Install it from: https://nodejs.org"
  echo "  Then re-run this installer."
  exit 1
fi

# Create install dir
mkdir -p "$INSTALL_DIR"

# Download CLI
curl -fsSL "$CLI_URL" -o "$BIN"
chmod +x "$BIN"

# Write install source to config (CLI will report install with device_id on first run)
mkdir -p "$CONFIG_DIR"
if [ ! -f "$CONFIG_FILE" ]; then
  printf '{"install_source":"%s"}' "$SOURCE" > "$CONFIG_FILE"
fi

# Add to PATH if needed
add_to_path() {
  local profile="$1"
  if [ -f "$profile" ] && ! grep -q 'clawbump/bin' "$profile" 2>/dev/null; then
    echo "" >> "$profile"
    echo '# ClawBump' >> "$profile"
    echo 'export PATH="$HOME/.clawbump/bin:$PATH"' >> "$profile"
    echo "  Added to $profile"
  fi
}

if echo "$PATH" | grep -q "$INSTALL_DIR"; then
  : # already in PATH
else
  add_to_path "$HOME/.zshrc"
  add_to_path "$HOME/.bashrc"
  add_to_path "$HOME/.bash_profile"
  echo ""
  echo "  PATH updated. Run: source ~/.zshrc  (or open a new terminal)"
fi

echo ""
echo "✓ ClawBump installed to $BIN"
echo "  Run: clawbump --version"
