#!/bin/bash
# Sync WAL archive to offsite host (astra) via Tailscale.
# Runs every 10 minutes via cron.
#
# Setup on astra:
#   mkdir -p /opt/backups/mnw/wal
#
# Setup on Hetzner (as makenotwork user):
#   Ensure SSH key-based auth to astra is configured (same as sync-backup-offsite.sh).
#
# Cron (as makenotwork user):
#   */10 * * * * /opt/makenotwork/sync-wal-offsite.sh >> /opt/makenotwork/wal-archive/sync.log 2>&1

set -euo pipefail

OFFSITE_HOST="100.106.221.39"  # astra (Tailscale IP)
OFFSITE_USER="max"
OFFSITE_DIR="/opt/backups/mnw/wal"
WAL_DIR="/opt/makenotwork/wal-archive"
OFFSITE_RETENTION_DAYS=7
WAM_URL="${WAM_URL:-http://127.0.0.1:7890}"

wam_alert() {
    local title="$1"
    local body="${2:-}"
    curl -sf -X POST "$WAM_URL/tickets" \
        -H "Content-Type: application/json" \
        -d "{\"title\": \"$title\", \"body\": \"$body\", \"priority\": \"high\", \"source\": \"wal-offsite\"}" \
        >/dev/null 2>&1 || true
}

if [ ! -d "$WAL_DIR" ]; then
    echo "[$(date -Iseconds)] WAL-OFFSITE: Archive directory $WAL_DIR does not exist"
    exit 0
fi

# Count files to sync
WAL_COUNT=$(find "$WAL_DIR" -maxdepth 1 -name '0*' -type f 2>/dev/null | wc -l)
if [ "$WAL_COUNT" -eq 0 ]; then
    exit 0
fi

echo "[$(date -Iseconds)] WAL-OFFSITE: Syncing $WAL_COUNT WAL segment(s) to ${OFFSITE_HOST}:${OFFSITE_DIR}"

if rsync -e "ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new" \
    --timeout=120 \
    "$WAL_DIR"/ \
    "${OFFSITE_USER}@${OFFSITE_HOST}:${OFFSITE_DIR}/"; then
    echo "[$(date -Iseconds)] WAL-OFFSITE: Transfer complete"
else
    echo "[$(date -Iseconds)] WAL-OFFSITE: Transfer FAILED"
    wam_alert "WAL offsite sync failed" "rsync to ${OFFSITE_HOST}:${OFFSITE_DIR} failed. Check Tailscale connectivity and SSH auth."
    exit 0
fi

# Prune old offsite WAL segments
DELETED=$(ssh -o ConnectTimeout=10 "${OFFSITE_USER}@${OFFSITE_HOST}" \
    "find ${OFFSITE_DIR} -name '0*' -mtime +${OFFSITE_RETENTION_DAYS} -delete -print 2>/dev/null | wc -l" \
    2>/dev/null || echo "0")
if [ "$DELETED" -gt 0 ]; then
    echo "[$(date -Iseconds)] WAL-OFFSITE: Pruned ${DELETED} segment(s) older than ${OFFSITE_RETENTION_DAYS} days"
fi
