#!/bin/bash
set -euo pipefail

ROOT="/Users/john/Project/Memind"
BACKUP="/Users/john/Project/.codex-baselines/Memind/wechat-service-agent-20260618-084500/.env.before-prod-mp-20260618-092652"
NODE_BIN="/opt/homebrew/opt/node@24/bin/node"

cd "$ROOT"

if [[ ! -f "$BACKUP" ]]; then
  echo "backup env not found: $BACKUP" >&2
  exit 1
fi

cp "$BACKUP" .env

PORT_PID="$(lsof -tiTCP:8081 -sTCP:LISTEN || true)"
if [[ -n "$PORT_PID" ]]; then
  kill "$PORT_PID"
  sleep 2
fi

nohup "$NODE_BIN" server.mjs >> h5.log 2>&1 &
echo $! > .h5.pid
sleep 3
curl -s http://127.0.0.1:8081/api/status
