#!/bin/bash
# hermes-standby-sync.sh — Periodic S3 sync for warm standby
# Pulls latest state from S3 every 10 min to keep app1-bu fresh.
# Runs in parallel with the watchdog. If failover happens,
# the latest data is already local.
set -euo pipefail

ENDPOINT="https://s3.us-east-1.wasabisys.com"
BUCKET="hermes-vps-backups"
SRC_PREFIX="live"
HERMES_HOME="${HOME}/.hermes"
LOG="/var/log/hermes-standby-sync.log"
LIVE_HOST="152.53.192.33"

source /opt/awscli-venv/bin/activate

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

# Don't sync if live box is unreachable (failover in progress)
if ! ping -c 1 -W 2 "${LIVE_HOST}" >/dev/null 2>&1; then
    log "Live box unreachable — skipping sync"
    exit 0
fi

log "Syncing from s3://${BUCKET}/${SRC_PREFIX}/..."
aws s3 sync "s3://${BUCKET}/${SRC_PREFIX}/" "${HERMES_HOME}/" \
    --endpoint-url "${ENDPOINT}" \
    --exclude "audio_cache/*" \
    --exclude "image_cache/*" \
    --exclude "cache/*" \
    --exclude "sandboxes/*" \
    --exclude "kanban/*" \
    --exclude "node/*" \
    --exclude "bin/*" \
    --exclude "logs/*" \
    --exclude "*.lock" \
    --exclude "state.db-shm" \
    --exclude "state.db-wal" \
    --no-progress 2>&1 >> "${LOG}"

log "Sync complete"
