#!/bin/bash
# ─────────────────────────────────────────────────────────────
# pull-platform-backup.sh
# Pulls the latest platform backup from main server to this VM.
# Run every hour via cron.
# ─────────────────────────────────────────────────────────────

MAIN_SERVER="root@173.249.20.244"
REMOTE_BACKUP_DIR="/root/backups/platform-backups"
LOCAL_BACKUP_DIR="/backups/platform"
LOG="/root/pull-platform.log"

log() { echo "$(date '+%Y-%m-%d %H:%M:%S') $1" | tee -a "$LOG"; }

mkdir -p "$LOCAL_BACKUP_DIR"

log "🔍 Checking latest platform backup on main server..."

LATEST=$(ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 $MAIN_SERVER \
    "ls -t ${REMOTE_BACKUP_DIR}/platform-backup-*.tar.gz 2>/dev/null | head -1")

if [ -z "$LATEST" ]; then
    log "❌ No platform backups found on main server at ${REMOTE_BACKUP_DIR}"
    exit 1
fi

BACKUP_NAME=$(basename "$LATEST")
LOCAL_PATH="$LOCAL_BACKUP_DIR/$BACKUP_NAME"

if [ -f "$LOCAL_PATH" ]; then
    log "✅ Already have latest: $BACKUP_NAME — nothing to pull"
    exit 0
fi

log "📥 Pulling: $BACKUP_NAME ..."
scp -o StrictHostKeyChecking=no -o ConnectTimeout=15 \
    "$MAIN_SERVER:$LATEST" "$LOCAL_PATH"

if [ $? -ne 0 ]; then
    log "❌ SCP failed — check SSH access to main server"
    rm -f "$LOCAL_PATH"   # remove partial file
    exit 1
fi

log "✅ Pulled successfully: $BACKUP_NAME"

# Keep only last 48 backups locally
log "🧹 Cleaning old backups (keeping last 48)..."
ls -t "$LOCAL_BACKUP_DIR"/platform-backup-*.tar.gz 2>/dev/null | tail -n +49 | xargs rm -f 2>/dev/null

log "Done."
