#!/usr/bin/env bash

# Encrypted PostgreSQL Backup Script
# Creates GPG-encrypted backups of all databases

set -e

BACKUP_DIR="${BACKUP_DIR:-/backups}"
BACKUP_DATE=$(date +%Y%m%d-%H%M%S)
GPG_RECIPIENT="${GPG_RECIPIENT:-backup@bakery-ia.com}"
NAMESPACE="${NAMESPACE:-bakery-ia}"

# Database list
DATABASES=(
  "auth-db"
  "tenant-db"
  "training-db"
  "forecasting-db"
  "sales-db"
  "external-db"
  "notification-db"
  "inventory-db"
  "recipes-db"
  "suppliers-db"
  "pos-db"
  "orders-db"
  "production-db"
  "alert-processor-db"
)

echo "Starting encrypted backup process..."
echo "Backup date: $BACKUP_DATE"
echo "Backup directory: $BACKUP_DIR"
echo "Namespace: $NAMESPACE"
echo ""

# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"

for db in "${DATABASES[@]}"; do
  echo "Backing up $db..."

  # Get pod name
  POD=$(kubectl get pods -n "$NAMESPACE" -l "app.kubernetes.io/name=$db" -o jsonpath='{.items[0].metadata.name}')

  if [ -z "$POD" ]; then
    echo "  ⚠️  Warning: Pod not found for $db, skipping"
    continue
  fi

  # Extract database name from environment
  DB_NAME=$(kubectl exec -n "$NAMESPACE" "$POD" -- sh -c 'echo $POSTGRES_DB')
  DB_USER=$(kubectl exec -n "$NAMESPACE" "$POD" -- sh -c 'echo $POSTGRES_USER')

  # Create backup file name
  BACKUP_FILE="$BACKUP_DIR/${db}_${DB_NAME}_${BACKUP_DATE}.sql.gz.gpg"

  # Perform backup with pg_dump, compress with gzip, encrypt with GPG
  kubectl exec -n "$NAMESPACE" "$POD" -- \
    sh -c "pg_dump -U $DB_USER -d $DB_NAME" | \
    gzip | \
    gpg --encrypt --recipient "$GPG_RECIPIENT" --trust-model always > "$BACKUP_FILE"

  # Get file size
  SIZE=$(du -h "$BACKUP_FILE" | cut -f1)

  echo "  ✓ Backup complete: $BACKUP_FILE ($SIZE)"
done

echo ""
echo "===================="
echo "✓ Backup process completed!"
echo ""
echo "Total backups created: ${#DATABASES[@]}"
echo "Backup location: $BACKUP_DIR"
echo "Backup date: $BACKUP_DATE"
echo ""
echo "To decrypt a backup:"
echo "  gpg --decrypt backup_file.sql.gz.gpg | gunzip > backup.sql"
echo ""
echo "To restore a backup:"
echo "  gpg --decrypt backup_file.sql.gz.gpg | gunzip | psql -U user -d database"
