#!/bin/bash
# ========================================
# Quick Deploy Script for cPanel/Production
# Run this every time you deploy updates
# ========================================

set -e  # Exit on error

echo "=================================================="
echo "🚀 Quick Production Deployment"
echo "=================================================="
echo ""

# Check if manage.py exists
if [ ! -f "manage.py" ]; then
    echo "❌ Error: manage.py not found"
    echo "   Run this script from your project root directory"
    exit 1
fi

# Step 1: Check environment
echo "1️⃣ Checking environment..."
if [ ! -f ".env" ]; then
    echo "   ⚠️  Warning: .env file not found"
    echo "   Create .env from .env.production template"
    exit 1
fi
echo "   ✅ Environment file found"
echo ""

# Step 2: Install/Update dependencies
echo "2️⃣ Installing dependencies..."
pip install -r requirements.txt --quiet
echo "   ✅ Dependencies installed"
echo ""

# Step 3: Apply migrations (CRITICAL!)
echo "3️⃣ Applying database migrations..."
echo "   This creates/updates database tables"
python manage.py migrate --no-input
echo "   ✅ Migrations applied"
echo ""

# Step 4: Collect static files
echo "4️⃣ Collecting static files..."
python manage.py collectstatic --no-input --clear
echo "   ✅ Static files collected"
echo ""

# Step 5: Check configuration
echo "5️⃣ Running configuration check..."
if python check_config.py 2>/dev/null; then
    echo "   ✅ Configuration OK"
else
    echo "   ⚠️  Configuration check not available (optional)"
fi
echo ""

# Step 6: Restart application
echo "6️⃣ Restarting application..."
if [ -d "tmp" ]; then
    touch tmp/restart.txt
    echo "   ✅ Restart triggered (Passenger)"
else
    echo "   ⚠️  tmp/ directory not found"
    echo "   Manual restart may be required"
fi
echo ""

# Success message
echo "=================================================="
echo "✅ Deployment Complete!"
echo "=================================================="
echo ""
echo "📋 What was done:"
echo "   ✓ Dependencies updated"
echo "   ✓ Database migrations applied"
echo "   ✓ Static files collected"
echo "   ✓ Application restarted"
echo ""
echo "🔍 Next steps:"
echo "   1. Visit your website: https://sponsor.enfantsoleilmonde.org"
echo "   2. Test the donation functionality"
echo "   3. Check error logs if issues occur"
echo ""
echo "📁 Logs location (if using cPanel):"
echo "   - Error logs via cPanel interface"
echo "   - Or check: logs/error.log (if configured)"
echo ""
