#!/usr/bin/env bash
# gbrain-refresh.sh — re-import vault + embed stale chunks.
# Runs while gateway is stopped (PGLite single-writer). Called by cron.
set -euo pipefail

GB="/root/.hermes/bin/gbrain-mcp"
VAULT="/root/.hermes/vault"
LOG="/root/.hermes/logs/gbrain-refresh.log"

log() { echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] $*" >> "$LOG"; }

log "stopping gateway"
systemctl stop hermes-gateway

# Give it a moment to release the PGLite lock
sleep 3

log "importing $VAULT"
"$GB" import "$VAULT" >> "$LOG" 2>&1 || log "IMPORT FAILED (exit $?)"

log "embedding stale"
"$GB" embed --stale >> "$LOG" 2>&1 || log "EMBED FAILED (exit $?)"

log "starting gateway"
systemctl start hermes-gateway

log "done"
