#!/bin/zsh set -euo pipefail ROOT_DIR="$(cd "$(dirname "$0")" && pwd)" BACKEND_DIR="$ROOT_DIR/backend" LOG_DIR="$ROOT_DIR/.wiseclaw/logs" PID_FILE="$ROOT_DIR/.wiseclaw/backend.pid" LOG_FILE="$LOG_DIR/backend.log" HEALTH_URL="http://127.0.0.1:8000/health" mkdir -p "$LOG_DIR" stop_existing() { if [[ -f "$PID_FILE" ]]; then local old_pid old_pid="$(cat "$PID_FILE" 2>/dev/null || true)" if [[ -n "${old_pid:-}" ]] && kill -0 "$old_pid" 2>/dev/null; then kill "$old_pid" 2>/dev/null || true sleep 1 fi rm -f "$PID_FILE" fi pkill -f "uvicorn app.main:app --host 0.0.0.0 --port 8000" >/dev/null 2>&1 || true } start_backend() { ( cd "$BACKEND_DIR" exec /bin/zsh -lc 'set -a; source .env >/dev/null 2>&1; exec .venv312/bin/python -m uvicorn app.main:app --host 0.0.0.0 --port 8000' ) >"$LOG_FILE" 2>&1 & echo $! > "$PID_FILE" } wait_for_health() { local attempt for attempt in {1..20}; do if curl -fsS "$HEALTH_URL" >/dev/null 2>&1; then return 0 fi sleep 1 done return 1 } stop_existing start_backend if wait_for_health; then echo "WiseClaw backend restarted." echo "PID: $(cat "$PID_FILE")" echo "Log: $LOG_FILE" exit 0 fi echo "WiseClaw backend failed to start. Check log: $LOG_FILE" >&2 exit 1