#!/usr/bin/env bash
# hermes-worker-on.command
# Double-click to start the Hermes Worker permanently (launchd).
# Installs the launchd agent and loads it — worker survives reboots.

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PLIST_SRC="$SCRIPT_DIR/com.hermes.worker.plist"
PLIST_DST="$HOME/Library/LaunchAgents/com.hermes.worker.plist"
HERMES_CONFIG="$HOME/.hermes/config.yaml"
HOOK_MARKER="# hermes-worker shared-folder hook"

echo "=== Hermes Worker — ON ==="
echo ""

if [ ! -f "$PLIST_SRC" ]; then
  echo "ERROR: com.hermes.worker.plist not found in $SCRIPT_DIR"
  echo "Make sure all worker files are in this folder."
  read -p "Press Enter to close..."
  exit 1
fi

echo "1. Configuring paths..."
mkdir -p "$HOME/Library/LaunchAgents" "$HOME/.hermes/skills"
sed -e "s|__HOME__|$HOME|g" \
    -e "s|/Users/klausk/dev/hermes-agent/hermes-worker|$SCRIPT_DIR|g" \
    "$PLIST_SRC" > "$PLIST_DST"

echo "2. Installing shared-folder skill..."
ln -sfn "$SCRIPT_DIR/skills/shared-folder" "$HOME/.hermes/skills/shared-folder"

echo "3. Installing shell hook (if not already present)..."
HOOK_CMD="$SCRIPT_DIR/hooks/block-raw-kobald-transfer.sh"
if [ ! -f "$HERMES_CONFIG" ]; then
  mkdir -p "$HOME/.hermes"
  cat > "$HERMES_CONFIG" <<EOF
$HOOK_MARKER
hooks:
  pre_tool_call:
    - matcher: "terminal"
      command: "$HOOK_CMD"
      timeout: 5
EOF
elif ! grep -qF "$HOOK_MARKER" "$HERMES_CONFIG" 2>/dev/null; then
  cat >> "$HERMES_CONFIG" <<EOF

$HOOK_MARKER
hooks:
  pre_tool_call:
    - matcher: "terminal"
      command: "$HOOK_CMD"
      timeout: 5
EOF
  echo "   Appended hook to $HERMES_CONFIG"
else
  echo "   Hook already configured in $HERMES_CONFIG"
fi

launchctl unload "$PLIST_DST" 2>/dev/null || true
launchctl load "$PLIST_DST"

echo "4. Worker started ✓"
echo ""
echo "Status:"
launchctl list com.hermes.worker 2>/dev/null || echo "  (checking...)"
echo ""
echo "Worker is now running and will auto-start on login."
echo "Logs: /tmp/hermes-worker-watchdog.log"
echo ""
read -p "Press Enter to close this window..."
