#!/bin/bash

# LuckyChit Database Backup Script
# Backs up PostgreSQL database with timestamped filename

set -e

# Configuration
DB_NAME="luckychit"
DB_USER="luckychit"
DB_HOST="localhost"
BACKUP_DIR="/home/luckychit/backups"
RETENTION_DAYS=7  # Keep backups for 7 days

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

# Generate timestamp
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/luckychit_backup_$TIMESTAMP.sql"

echo "🗄️  Starting database backup..."
echo "Database: $DB_NAME"
echo "Backup file: $BACKUP_FILE"
echo ""

# Perform backup
pg_dump -U "$DB_USER" -h "$DB_HOST" "$DB_NAME" > "$BACKUP_FILE"

# Check if backup was successful
if [ $? -eq 0 ]; then
    # Get file size
    FILE_SIZE=$(du -h "$BACKUP_FILE" | cut -f1)
    
    echo "✅ Backup completed successfully!"
    echo "📦 File size: $FILE_SIZE"
    echo "📁 Location: $BACKUP_FILE"
    
    # Compress backup (optional)
    echo ""
    echo "🗜️  Compressing backup..."
    gzip "$BACKUP_FILE"
    COMPRESSED_FILE="$BACKUP_FILE.gz"
    COMPRESSED_SIZE=$(du -h "$COMPRESSED_FILE" | cut -f1)
    
    echo "✅ Compression completed!"
    echo "📦 Compressed size: $COMPRESSED_SIZE"
    echo "📁 Location: $COMPRESSED_FILE"
    
    # Remove old backups
    echo ""
    echo "🧹 Cleaning up old backups (older than $RETENTION_DAYS days)..."
    DELETED_COUNT=$(find "$BACKUP_DIR" -name "luckychit_backup_*.sql.gz" -mtime +$RETENTION_DAYS -delete -print | wc -l)
    
    if [ "$DELETED_COUNT" -gt 0 ]; then
        echo "✅ Deleted $DELETED_COUNT old backup(s)"
    else
        echo "✅ No old backups to delete"
    fi
    
    # Show remaining backups
    echo ""
    echo "📊 Current backups:"
    ls -lh "$BACKUP_DIR"/luckychit_backup_*.sql.gz 2>/dev/null || echo "No backups found"
    
    echo ""
    echo "✅ Backup process completed successfully!"
    
else
    echo "❌ Backup failed!"
    exit 1
fi

