#!/bin/bash
set -euo pipefail

# Database Backup Script
# Creates automated backups of PostgreSQL database

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

BACKUP_DIR="${BACKUP_DIR:-/backups}"
RETENTION_DAYS="${RETENTION_DAYS:-30}"
NAMESPACE="${NAMESPACE:-api}"

log_info() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] [INFO] $1"
}

log_error() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] [ERROR] $1" >&2
}

# Create backup directory
mkdir -p "$BACKUP_DIR"

# Get database credentials
DB_NAME="${DB_NAME:-sankofa}"
DB_USER="${DB_USER:-sankofa}"

# Generate backup filename
BACKUP_FILE="$BACKUP_DIR/sankofa-backup-$(date +%Y%m%d-%H%M%S).sql.gz"

log_info "Starting database backup..."

# Create backup
if kubectl get deployment postgres -n "$NAMESPACE" &>/dev/null; then
    # Backup from Kubernetes deployment
    kubectl exec -n "$NAMESPACE" deployment/postgres -- \
        pg_dump -U "$DB_USER" "$DB_NAME" | gzip > "$BACKUP_FILE"
elif kubectl get statefulset postgres -n "$NAMESPACE" &>/dev/null; then
    # Backup from StatefulSet
    kubectl exec -n "$NAMESPACE" statefulset/postgres -- \
        pg_dump -U "$DB_USER" "$DB_NAME" | gzip > "$BACKUP_FILE"
else
    log_error "PostgreSQL deployment not found in namespace $NAMESPACE"
    exit 1
fi

# Verify backup
if [ ! -f "$BACKUP_FILE" ] || [ ! -s "$BACKUP_FILE" ]; then
    log_error "Backup file is missing or empty"
    exit 1
fi

BACKUP_SIZE=$(du -h "$BACKUP_FILE" | cut -f1)
log_info "Backup completed: $BACKUP_FILE ($BACKUP_SIZE)"

# Cleanup old backups
log_info "Cleaning up backups older than $RETENTION_DAYS days..."
find "$BACKUP_DIR" -name "sankofa-backup-*.sql.gz" -mtime +$RETENTION_DAYS -delete

log_info "Backup process completed successfully"

