#!/bin/bash
set -e

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

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DEPLOYMENT_DIR="$(dirname "$SCRIPT_DIR")"
BACKUP_DIR="$DEPLOYMENT_DIR/backups"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")

# Load environment variables
if [ -f "$DEPLOYMENT_DIR/.env" ]; then
    source "$DEPLOYMENT_DIR/.env"
fi

# Default values
DB_USER="${DB_USER:-agenda}"
DB_NAME="${DB_NAME:-agenda_tasks}"

# Create backup directory
mkdir -p "$BACKUP_DIR"

echo -e "${GREEN}=== Database Backup ===${NC}"
echo -e "${YELLOW}Database: $DB_NAME${NC}"
echo -e "${YELLOW}User: $DB_USER${NC}"

# Create backup
BACKUP_FILE="$BACKUP_DIR/${DB_NAME}_${TIMESTAMP}.sql.gz"

echo -e "${GREEN}Creating backup: $BACKUP_FILE${NC}"

cd "$DEPLOYMENT_DIR/docker"

docker compose exec -T db pg_dump -U "$DB_USER" "$DB_NAME" | gzip > "$BACKUP_FILE"

if [ -f "$BACKUP_FILE" ]; then
    BACKUP_SIZE=$(du -h "$BACKUP_FILE" | cut -f1)
    echo -e "${GREEN}Backup created successfully!${NC}"
    echo -e "${YELLOW}Size: $BACKUP_SIZE${NC}"
else
    echo -e "${RED}Backup failed!${NC}"
    exit 1
fi

# Clean up old backups (keep last 7 days)
echo -e "${GREEN}Cleaning up old backups...${NC}"
find "$BACKUP_DIR" -name "*.sql.gz" -mtime +7 -delete

# List current backups
echo -e "${GREEN}Current backups:${NC}"
ls -lh "$BACKUP_DIR"/*.sql.gz 2>/dev/null || echo "No backups found"

echo -e "${GREEN}=== Backup complete! ===${NC}"
