#!/bin/bash

# YouTube Clone Deployment Script
# Author: AI Assistant
# Description: Deploy YouTube Clone to production server

echo "🚀 Starting YouTube Clone Deployment..."

# Set environment variables
export DEPLOYPATH="/home/fnkjyinw/youtube"
export VIRTUAL_ENV="/home/fnkjyinw/virtualenv/youtube/2.7/bin/activate"

echo "📁 Deployment path: $DEPLOYPATH"
echo "🐍 Python virtual environment: $VIRTUAL_ENV"

# Activate virtual environment
echo "🔧 Activating Python virtual environment..."
source $VIRTUAL_ENV

# Check if activation was successful
if [ $? -eq 0 ]; then
    echo "✅ Virtual environment activated successfully"
else
    echo "❌ Failed to activate virtual environment"
    exit 1
fi

# Navigate to project directory
echo "📂 Navigating to project directory..."
cd /home/fnkjyinw/youtube

# Check if we're in the right directory
if [ "$(pwd)" != "/home/fnkjyinw/youtube" ]; then
    echo "❌ Failed to navigate to project directory"
    exit 1
fi

echo "✅ Successfully navigated to project directory"

# Install dependencies if requirements.txt exists
if [ -f "requirements.txt" ]; then
    echo "📦 Installing Python dependencies..."
    pip install -r requirements.txt
    
    if [ $? -eq 0 ]; then
        echo "✅ Dependencies installed successfully"
    else
        echo "❌ Failed to install dependencies"
        exit 1
    fi
else
    echo "⚠️  No requirements.txt found, skipping dependency installation"
fi

# Collect static files
echo "📁 Collecting static files..."
python manage.py collectstatic --noinput

if [ $? -eq 0 ]; then
    echo "✅ Static files collected successfully"
else
    echo "❌ Failed to collect static files"
    exit 1
fi

# Run database migrations
echo "🗄️ Running database migrations..."
python manage.py migrate

if [ $? -eq 0 ]; then
    echo "✅ Database migrations completed successfully"
else
    echo "❌ Failed to run database migrations"
    exit 1
fi

# Create superuser if doesn't exist (optional)
echo "👤 Checking for 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():
    print('Creating superuser...')
    User.objects.create_superuser('admin', 'admin@example.com', 'admin123')
    print('Superuser created successfully')
else:
    print('Superuser already exists')
EOF

if [ $? -eq 0 ]; then
    echo "✅ Superuser check completed"
    echo "   Username: admin"
    echo "   Email: admin@example.com"
    echo "   Password: admin123"
    echo "   ⚠️  Please change password after first login!"
else
    echo "❌ Failed to check/create superuser"
fi

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

if [ $? -eq 0 ]; then
    echo "✅ File permissions set successfully"
else
    echo "❌ Failed to set file permissions"
fi

# Restart web server (using Gunicorn for production)
echo "🔄 Restarting web server..."
pkill -f gunicorn  # Stop any existing Gunicorn processes

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

# Check if Gunicorn started successfully
sleep 3
if pgrep -f gunicorn > /dev/null; then
    echo "✅ Gunicorn server started successfully"
    echo "🌐 Server running on: http://127.0.0.1:8000"
    echo "📊 To view logs: tail -f /var/log/gunicorn.log"
    echo "🛑 To stop server: pkill -f gunicorn"
else
    echo "❌ Failed to start Gunicorn server"
    exit 1
fi

echo "🎉 Deployment completed successfully!"
echo ""
echo "📋 Deployment Summary:"
echo "   ✅ Virtual environment: $VIRTUAL_ENV"
echo "   ✅ Project directory: $DEPLOYPATH"
echo "   ✅ Dependencies: Installed"
echo "   ✅ Database: Migrated"
echo "   ✅ Static files: Collected"
echo "   ✅ File permissions: Set"
echo "   ✅ Web server: Running"
echo ""
echo "🌐 Your YouTube Clone is now live!"
echo "📝 Don't forget to:"
echo "   1. Update the domain in your Nginx/Apache config"
echo "   2. Set up SSL certificate for HTTPS"
echo "   3. Configure firewall rules"
echo "   4. Set up monitoring and logging"
