#!/bin/bash

# Simple YouTube Clone Deployment Script
# Fixed version with better error handling

echo "🚀 Starting YouTube Clone Deployment..."

# Set variables
DEPLOYPATH="/home/fnkjyinw/youtube"
VENV_PATH="/home/fnkjyinw/virtualenv/youtube/2.7/bin/activate"

echo "📁 Deployment path: $DEPLOYPATH"

# Function to check command success
check_success() {
    if [ $? -eq 0 ]; then
        echo "✅ $1 completed successfully"
        return 0
    else
        echo "❌ $1 failed"
        return 1
    fi
}

# Navigate to project directory
echo "📂 Navigating to project directory..."
cd $DEPLOYPATH || exit 1

# Activate virtual environment
echo "🔧 Activating virtual environment..."
source $VENV_PATH || exit 1

# Install dependencies
echo "📦 Installing dependencies..."
if [ -f "requirements.txt" ]; then
    pip install -r requirements.txt
    check_success "Dependency installation" || exit 1
else
    echo "⚠️ No requirements.txt found"
fi

# Run migrations
echo "🗄️ Running migrations..."
python manage.py migrate
check_success "Database migrations" || exit 1

# Collect static files
echo "📁 Collecting static files..."
python manage.py collectstatic --noinput
check_success "Static file collection" || exit 1

# Create superuser (simplified)
echo "👤 Creating superuser..."
python manage.py shell << 'EOF'
from django.contrib.auth import get_user_model
User = get_user_model()
if not User.objects.filter(username='admin').exists():
    User.objects.create_superuser('admin', 'admin@example.com', 'admin123')
    print('Superuser created')
else:
    print('Superuser already exists')
EOF

# Set permissions
echo "🔒 Setting permissions..."
chmod -R 755 $DEPLOYPATH
chmod -R 777 $DEPLOYPATH/static
chmod -R 777 $DEPLOYPATH/media

# Start Gunicorn
echo "🚀 Starting server..."
pkill -f gunicorn 2>/dev/null
sleep 2
gunicorn --workers 3 --bind 127.0.0.1:8000 youtube_project.wsgi:application --daemon

# Check if server is running
sleep 3
if pgrep -f gunicorn > /dev/null; then
    echo "✅ Server started successfully!"
    echo "🌐 Running on: http://127.0.0.1:8000"
    echo "👤 Admin: admin / admin123"
    echo "🛑 Stop: pkill -f gunicorn"
else
    echo "❌ Server failed to start"
    echo "🔍 Check logs: python manage.py runserver 0.0.0.0:8001"
fi

echo "🎉 Deployment complete!"
