#!/usr/bin/env bash
# Nexus — MySQL 定时备份（Docker 1Panel / 宿主机）
#
#   0 3 * * * NEXUS_ROOT=/opt/nexus /opt/nexus/deploy/db_backup.sh >> /var/log/nexus_backup.log 2>&1
#
# 亦可通过: sudo bash deploy/install_ops_cron.sh
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
NEXUS_ROOT="${NEXUS_ROOT:-$(dirname "$SCRIPT_DIR")}"
BACKUP_DIR="${NEXUS_BACKUP_DIR:-/var/backups/nexus}"
RETENTION_DAYS="${NEXUS_BACKUP_RETENTION_DAYS:-30}"
DUMP_SH="${SCRIPT_DIR}/mysql_dump_to_file.sh"

if [[ ! -f "$DUMP_SH" ]]; then
    echo "[$(date)] ERROR: missing $DUMP_SH"
    exit 1
fi
chmod +x "$DUMP_SH" 2>/dev/null || true

mkdir -p "$BACKUP_DIR"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
RAW_FILE="${BACKUP_DIR}/nexus_daily_${TIMESTAMP}.sql"
BACKUP_FILE="${RAW_FILE}.gz"

echo "[$(date)] Starting backup → $BACKUP_FILE"
if ! NEXUS_ROOT="$NEXUS_ROOT" bash "$DUMP_SH" --output "$RAW_FILE" --root "$NEXUS_ROOT"; then
    echo "[$(date)] ERROR: mysqldump failed"
    rm -f "$RAW_FILE"
    exit 1
fi

gzip -f "$RAW_FILE"
if [[ ! -f "$BACKUP_FILE" ]]; then
    echo "[$(date)] ERROR: backup file not created"
    exit 1
fi

SIZE="$(du -h "$BACKUP_FILE" | cut -f1)"
echo "[$(date)] Backup completed: $BACKUP_FILE ($SIZE)"

DELETED="$(find "$BACKUP_DIR" -name 'nexus_*.sql.gz' -mtime +"${RETENTION_DAYS}" -delete -print 2>/dev/null | wc -l)"
if [[ "$DELETED" -gt 0 ]]; then
    echo "[$(date)] Cleaned up $DELETED old backup(s) (>${RETENTION_DAYS} days)"
fi

echo "[$(date)] Backup process complete"
