#!/bin/bash

# Configuration
BACKUP_DIR="/backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
DB_HOST="mold_cost_db"
DB_NAME="mold_cost"
DB_USER="postgres"
DB_PASSWORD="postgres"

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

# Set PostgreSQL password environment variable
export PGPASSWORD="$DB_PASSWORD"

# Create backup with error handling
echo "Creating database backup at $(date)..."
if pg_dump -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" --no-password | gzip > "$BACKUP_DIR/backup_$TIMESTAMP.sql.gz"; then
    echo "Backup completed successfully: backup_$TIMESTAMP.sql.gz"
    
    # Keep only the last 7 backups
    echo "Cleaning up old backups..."
    ls -t "$BACKUP_DIR"/backup_*.sql.gz | tail -n +8 | xargs -r rm
    
    # Verify backup file exists and has content
    if [ -f "$BACKUP_DIR/backup_$TIMESTAMP.sql.gz" ] && [ -s "$BACKUP_DIR/backup_$TIMESTAMP.sql.gz" ]; then
        echo "Backup verification successful: $(du -h "$BACKUP_DIR/backup_$TIMESTAMP.sql.gz" | cut -f1)"
    else
        echo "ERROR: Backup file is empty or missing!"
        exit 1
    fi
else
    echo "ERROR: Backup failed!"
    exit 1
fi

# Clear password from environment
unset PGPASSWORD 