#!/bin/bash

# Server Setup Script for Production
# This script sets up the Laravel application for direct hosting on the production server

set -e

echo "🚀 Setting up Production Server for Laravel Application"
echo "======================================================"
echo "PHP Version: 8.3+"
echo "MySQL Version: 9.0+"
echo "Nginx Version: 1.24.0"
echo "Project Path: /var/www/seraph3"
echo ""

# Check if running as root user (not just with sudo)
if [[ $EUID -eq 0 && -z "$SUDO_USER" ]]; then
   echo "❌ This script should not be run as root user directly"
   echo "💡 Use: sudo ./server-setup.sh"
   exit 1
fi

# Check if we're in the correct directory
if [[ ! -f "composer.json" ]]; then
    echo "❌ Please run this script from the project root directory"
    exit 1
fi

echo "✅ Prerequisites check passed"

# Step 1: Install PHP-FPM and required extensions
echo "📦 Installing PHP-FPM and required extensions..."
sudo apt update
sudo apt install -y software-properties-common
sudo add-apt-repository ppa:ondrej/php -y
sudo apt update
sudo apt install -y php8.3-fpm php8.3-mysql php8.3-redis php8.3-mbstring php8.3-xml php8.3-curl php8.3-zip php8.3-gd php8.3-bcmath php8.3-opcache php8.3-ldap php8.3-cli php8.3-common php8.3-intl php8.3-dom

# Install LDAP system libraries
echo "📦 Installing LDAP support..."
sudo apt install -y libldap2-dev libnss-ldap libpam-ldap ldap-utils

# Step 2: Configure PHP-FPM
echo "⚙️ Configuring PHP-FPM..."
sudo sed -i 's/^listen = .*/listen = 127.0.0.1:9000/' /etc/php/8.3/fpm/pool.d/www.conf

# Step 3: Start and enable PHP-FPM
echo "🚀 Starting PHP-FPM..."
sudo systemctl start php8.3-fpm
sudo systemctl enable php8.3-fpm

# Step 4: Configure nginx
echo "🌐 Configuring nginx..."
sudo cp nginx/direct-hosting-production.conf /etc/nginx/sites-available/seraph3
sudo ln -sf /etc/nginx/sites-available/seraph3 /etc/nginx/sites-enabled/

# Step 5: Test nginx configuration
echo "🔍 Testing nginx configuration..."
sudo nginx -t

# Step 6: Set proper permissions
echo "🔐 Setting file permissions..."
sudo chown -R www-data:www-data storage bootstrap/cache
sudo chmod -R 775 storage bootstrap/cache

# Step 7: Start system services
echo "🚀 Starting system services..."
sudo systemctl start mysql
sudo systemctl start redis-server
sudo systemctl start php8.3-fpm
sudo systemctl start nginx

# Step 8: Wait for MySQL to be ready
echo "⏳ Waiting for MySQL to be ready..."
sleep 10

# Step 9: Configure Laravel environment
echo "🔧 Configuring Laravel environment..."

# Check if .env exists, if not create it
if [ ! -f .env ]; then
    echo "📝 Creating .env file..."
    cp .env.example .env
    php artisan key:generate
fi

# Update .env for production
echo "🔧 Updating .env for production..."
sed -i.bak 's/DB_HOST=.*/DB_HOST=127.0.0.1/' .env
sed -i.bak 's/REDIS_HOST=.*/REDIS_HOST=127.0.0.1/' .env
sed -i.bak 's/APP_ENV=.*/APP_ENV=production/' .env
sed -i.bak 's/APP_DEBUG=.*/APP_DEBUG=false/' .env

# Step 10: Run Laravel setup
echo "🗄️ Running database migrations..."
php artisan migrate --force

echo "🧹 Clearing application caches..."
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear

echo "⚡ Optimizing for production..."
php artisan config:cache
php artisan route:cache
php artisan view:cache
composer install --optimize-autoloader --no-dev

# Step 11: Reload nginx
echo "🔄 Reloading nginx..."
sudo systemctl reload nginx

echo ""
echo "✅ Production setup completed successfully!"
echo ""
echo "📋 Next steps:"
echo "1. Configure SSL certificate:"
echo "   sudo certbot --nginx -d seraph-dev.computerassistance.uk"
echo ""
echo "2. Configure firewall:"
echo "   sudo ufw allow 80"
echo "   sudo ufw allow 443"
echo "   sudo ufw allow 3306"
echo "   sudo ufw allow 6379"
echo "   sudo ufw allow 8080"
echo ""
echo "3. Set up monitoring and backups (see docs/SERVER_SETUP_GUIDE.md)"
echo ""
echo "🌐 Access points:"
echo "- Laravel Application: https://seraph-dev.computerassistance.uk"
echo "- Adminer (Database): https://seraph-dev.computerassistance.uk:8080"
echo "- MySQL: localhost:3306"
echo "- Redis: localhost:6379"
echo ""
echo "📚 For detailed instructions, see: docs/SERVER_SETUP_GUIDE.md"
echo ""
echo "🔍 Service status:"
echo "PHP-FPM: $(sudo systemctl is-active php8.3-fpm)"
echo "Nginx: $(sudo systemctl is-active nginx)"
echo "MySQL: $(sudo systemctl is-active mysql)"
echo "Redis: $(sudo systemctl is-active redis-server)" 