#!/bin/bash

# Fix Server Script - Run this directly on the server
echo "🔧 Fixing Server Configuration"
echo "=============================="

# 1. Check current directory structure
echo "📁 Current directory structure:"
ls -la /var/www/domain-rotator/

# 2. Move files to correct location
echo "📦 Moving files to correct location..."
if [ -d "/var/www/domain-rotator/rotator-jago/app" ]; then
    echo "Moving from rotator-jago/app to root..."
    cp -r /var/www/domain-rotator/rotator-jago/app/* /var/www/domain-rotator/
    rm -rf /var/www/domain-rotator/rotator-jago
    echo "✅ Files moved successfully"
else
    echo "Files already in correct location"
fi

# 3. Set correct permissions
echo "🔐 Setting permissions..."
chown -R www-data:www-data /var/www/domain-rotator
chmod -R 755 /var/www/domain-rotator
chmod -R 775 /var/www/domain-rotator/storage 2>/dev/null || echo "Storage directory not found"
chmod -R 775 /var/www/domain-rotator/bootstrap/cache 2>/dev/null || echo "Bootstrap cache directory not found"

# 4. Create proper Nginx configuration
echo "🌐 Creating Nginx configuration..."
cat > /etc/nginx/sites-available/rotator-jago.online << 'EOF'
server {
    listen 80;
    server_name rotator-jago.online www.rotator-jago.online;
    root /var/www/domain-rotator/public;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_index index.php;
    }
}
EOF

# 5. Enable site
echo "🔗 Enabling Nginx site..."
ln -sf /etc/nginx/sites-available/rotator-jago.online /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default

# 6. Test Nginx configuration
echo "🧪 Testing Nginx configuration..."
nginx -t

# 7. Restart services
echo "🔄 Restarting services..."
systemctl restart nginx
systemctl restart php8.4-fpm

# 8. Check status
echo "📊 Checking service status..."
systemctl status nginx --no-pager
systemctl status php8.4-fpm --no-pager

# 9. Check final directory structure
echo "📁 Final directory structure:"
ls -la /var/www/domain-rotator/
ls -la /var/www/domain-rotator/public/

echo ""
echo "✅ Server fix completed!"
echo "🌐 Try accessing: http://rotator-jago.online"
