#!/bin/bash

# Final YouTube Clone Deployment Script
# Ultra-simple version that should work on any Linux server

echo "🚀 YouTube Clone Deployment Starting..."

# Go to project directory
cd /home/fnkjyinw/youtube || {
    echo "❌ Cannot navigate to /home/fnkjyinw/youtube"
    exit 1
}

echo "✅ In project directory: $(pwd)"

# Activate virtual environment
if [ -f "/home/fnkjyinw/virtualenv/youtube/2.7/bin/activate" ]; then
    source /home/fnkjyinw/virtualenv/youtube/2.7/bin/activate
    echo "✅ Virtual environment activated"
else
    echo "❌ Virtual environment not found"
    exit 1
fi

# Install basic dependencies
echo "📦 Installing dependencies..."
pip install django==1.11 pillow django-crispy-forms gunicorn

# Run Django migrations
echo "🗄️ Running migrations..."
python manage.py migrate || {
    echo "❌ Migration failed"
    exit 1
}

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

# Create superuser automatically
echo "👤 Creating admin user..."
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('Admin user created: admin/admin123')
else:
    print('Admin user already exists')
EOF

# Set permissions
echo "🔒 Setting permissions..."
chmod -R 755 /home/fnkjyinw/youtube
chmod -R 777 /home/fnkjyinw/youtube/static 2>/dev/null
chmod -R 777 /home/fnkjyinw/youtube/media 2>/dev/null

# Stop any existing server
echo "🛑 Stopping existing server..."
pkill -f gunicorn 2>/dev/null
sleep 2

# Start Gunicorn server
echo "🚀 Starting server..."
gunicorn --workers 3 --bind 127.0.0.1:8000 youtube_project.wsgi:application --daemon

# Wait and check
sleep 3
if pgrep -f gunicorn > /dev/null; then
    echo "✅ Server started successfully!"
    echo ""
    echo "🌐 Your YouTube Clone is running!"
    echo "📍 Local: http://127.0.0.1:8000"
    echo "👤 Admin: http://127.0.0.1:8000/admin/"
    echo "🔑 Login: admin / admin123"
    echo ""
    echo "🛑 To stop: pkill -f gunicorn"
    echo "📊 To test: curl http://127.0.0.1:8000"
else
    echo "❌ Server failed to start"
    echo "🔍 Trying development server..."
    python manage.py runserver 0.0.0.0:8000
fi

echo "🎉 Deployment complete!"
