#!/bin/bash

# LuckyChit Database Backup Script

set -e

DB_NAME="luckychit"
DB_USER="luckychit"
DB_HOST="localhost"
BACKUP_DIR="/home/luckychit/backups"
RETENTION_DAYS=7

mkdir -p "$BACKUP_DIR"

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 ""

pg_dump -U "$DB_USER" -h "$DB_HOST" "$DB_NAME" > "$BACKUP_FILE"

if [ $? -eq 0 ]; then
    FILE_SIZE=$(du -h "$BACKUP_FILE" | cut -f1)
    echo "✅ Backup completed successfully!"
    echo "📦 File size: $FILE_SIZE"
    
    echo ""
    echo "🗜️  Compressing backup..."
    gzip "$BACKUP_FILE"
    COMPRESSED_SIZE=$(du -h "$BACKUP_FILE.gz" | cut -f1)
    echo "✅ Compressed size: $COMPRESSED_SIZE"
    
    echo ""
    echo "🧹 Cleaning up old backups (older than $RETENTION_DAYS days)..."
    DELETED=$(find "$BACKUP_DIR" -name "luckychit_backup_*.sql.gz" -mtime +$RETENTION_DAYS -delete -print | wc -l)
    echo "✅ Deleted $DELETED old backup(s)"
    
    echo ""
    echo "📊 Current backups:"
    ls -lh "$BACKUP_DIR"/luckychit_backup_*.sql.gz 2>/dev/null || echo "No backups found"
    
    echo ""
    echo "✅ Backup complete: $BACKUP_FILE.gz"
else
    echo "❌ Backup failed!"
    exit 1
fi

