#!/bin/bash
# Backup Configuration Files and Validator Keys
# Creates encrypted backups of critical files

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARNING]${NC} $1"; }

# Backup configuration
BACKUP_BASE="${BACKUP_BASE:-/backup/smom-dbis-138}"
BACKUP_DIR="$BACKUP_BASE/$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BACKUP_DIR"

log_info "Creating backup in: $BACKUP_DIR"

# Backup deployment configs (if on Proxmox host)
if [[ -d "$PROJECT_ROOT/config" ]]; then
    log_info "Backing up deployment configuration files..."
    tar -czf "$BACKUP_DIR/deployment-configs.tar.gz" -C "$PROJECT_ROOT" config/ || {
        log_warn "Failed to backup deployment configs (may not be on Proxmox host)"
    }
fi

# Backup source project configs (if accessible)
SOURCE_PROJECT="${SOURCE_PROJECT:-/home/intlc/projects/smom-dbis-138}"
if [[ -d "$SOURCE_PROJECT/config" ]]; then
    log_info "Backing up source project configuration files..."
    tar -czf "$BACKUP_DIR/source-configs.tar.gz" -C "$SOURCE_PROJECT" config/ || {
        log_warn "Failed to backup source configs"
    }
    
    # Backup validator keys (encrypted if gpg available)
    if [[ -d "$SOURCE_PROJECT/keys/validators" ]]; then
        log_info "Backing up validator keys..."
        if command -v gpg >/dev/null 2>&1; then
            tar -czf - -C "$SOURCE_PROJECT" keys/validators/ | \
                gpg -c --cipher-algo AES256 --batch --yes \
                --passphrase "${BACKUP_PASSPHRASE:-}" \
                > "$BACKUP_DIR/validator-keys.tar.gz.gpg" 2>/dev/null || {
                log_warn "GPG encryption failed, backing up without encryption"
                tar -czf "$BACKUP_DIR/validator-keys.tar.gz" -C "$SOURCE_PROJECT" keys/validators/
            }
        else
            log_warn "GPG not available, backing up without encryption"
            tar -czf "$BACKUP_DIR/validator-keys.tar.gz" -C "$SOURCE_PROJECT" keys/validators/
        fi
    fi
fi

# Backup container configurations (if pct available)
if command -v pct >/dev/null 2>&1; then
    log_info "Backing up container configurations..."
    mkdir -p "$BACKUP_DIR/containers"
    for vmid in 1000 1001 1002 1003 1004 1500 1501 1502 1503 2500 2501 2502; do
        if pct config "$vmid" >/dev/null 2>&1; then
            pct config "$vmid" > "$BACKUP_DIR/containers/container-$vmid.conf" 2>/dev/null || true
        fi
    done
    log_success "Container configs backed up"
fi

# Create backup manifest
cat > "$BACKUP_DIR/manifest.txt" <<MANIFEST
Backup created: $(date)
Backup location: $BACKUP_DIR
Contents:
  - deployment-configs.tar.gz
  - source-configs.tar.gz
  - validator-keys.tar.gz[.gpg]
  - containers/ (container configurations)

Restore instructions:
  1. Extract configs: tar -xzf deployment-configs.tar.gz
  2. Extract source configs: tar -xzf source-configs.tar.gz
  3. Decrypt and extract keys: gpg -d validator-keys.tar.gz.gpg | tar -xzf -
  4. Restore container configs from containers/ directory
MANIFEST

log_success "Backup complete: $BACKUP_DIR"

# Retention policy: Keep backups for 30 days
log_info "Cleaning up old backups (retention: 30 days)..."
find "$BACKUP_BASE" -mindepth 1 -maxdepth 1 -type d -mtime +30 -exec rm -rf {} \; 2>/dev/null || true

log_success "Backup process complete!"
