#!/bin/bash
# =============================================================================
# Aurora Database Backup Script
# =============================================================================
# Creates a timestamped PostgreSQL backup and retains the last 10 backups.
#
# Usage: ./db-backup.sh
# =============================================================================

set -e

# Load environment variables safely
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/lib/load-env.sh"
load_env

PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
BACKUP_DIR="$PROJECT_DIR/shared/db/backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/backup_$TIMESTAMP.sql"

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

echo -e "${YELLOW}💾 Starting database backup...${NC}"

mkdir -p "$BACKUP_DIR"

# Ensure the backup directory is writable (may have been created by Docker/root)
if [ ! -w "$BACKUP_DIR" ]; then
  echo -e "  ${YELLOW}⚠️  Fixing backup directory permissions...${NC}"
  chmod u+w "$BACKUP_DIR" 2>/dev/null || sudo chown "$(whoami)" "$BACKUP_DIR" 2>/dev/null || {
    echo -e "  ${RED}✗${NC} Cannot write to $BACKUP_DIR"
    echo "  Run: sudo chown $(whoami) $BACKUP_DIR"
    exit 1
  }
fi

if docker ps | grep -q aurora_db; then
  # Try to dump the database
  if docker exec aurora_db pg_dump -U "${DB_USER:-auroradev}" "${DB_NAME:-auroradev}" > "$BACKUP_FILE"; then
     # Check if backup file is not empty
     if [ -s "$BACKUP_FILE" ]; then
       echo -e "  ${GREEN}✓${NC} Backup successful!"
       echo -e "  📂 File: $BACKUP_FILE"
       echo -e "  📏 Size: $(du -h "$BACKUP_FILE" | cut -f1)"
       
       # Keep only last 10 backups (cross-platform: works on macOS and Linux)
       cd "$BACKUP_DIR"
       OLD_BACKUPS=$(ls -t backup_*.sql 2>/dev/null | tail -n +11)
       if [ -n "$OLD_BACKUPS" ]; then
         echo "$OLD_BACKUPS" | xargs rm --
         echo -e "  ${GREEN}✓${NC} Pruned old backups"
       fi
     else
       echo -e "  ${RED}✗${NC} Backup created but empty. Something went wrong."
       rm -f "$BACKUP_FILE"
       exit 1
     fi
  else
     echo -e "  ${RED}✗${NC} pg_dump failed."
     rm -f "$BACKUP_FILE"
     exit 1
  fi
else
  echo -e "  ${RED}✗${NC} Database container (aurora_db) is not running!"
  exit 1
fi
