#!/bin/bash
# Nginx Setup Script for Homelab
# Run with: sudo bash nginx-setup.sh

set -e

echo "Setting up Nginx reverse proxy..."

# Install nginx and SSL tools
echo "Installing nginx and certbot..."
pacman -S --noconfirm nginx certbot certbot-nginx

# Create sites directories (some distributions don't have these)
mkdir -p /etc/nginx/sites-available
mkdir -p /etc/nginx/sites-enabled

# Enable sites-enabled in main nginx.conf if not already
if ! grep -q "sites-enabled" /etc/nginx/nginx.conf; then
    echo "Adding sites-enabled include to nginx.conf..."
    sed -i '/http {/a \ \ \ \ include /etc/nginx/sites-enabled/*;' /etc/nginx/nginx.conf
fi

# Copy site configuration
echo "Copying site configuration..."
cp nginx-homelab.conf /etc/nginx/sites-available/homelab

# Enable the site
echo "Enabling homelab site..."
ln -sf /etc/nginx/sites-available/homelab /etc/nginx/sites-enabled/homelab

# Create web root directory
echo "Creating web root directory..."
mkdir -p /var/www/homelab
chown -R hoborg:hoborg /var/www/homelab

# Test nginx configuration
echo "Testing nginx configuration..."
nginx -t

# Enable and start nginx
echo "Starting nginx service..."
systemctl enable nginx
systemctl start nginx

echo ""
echo "✅ Nginx setup complete!"
echo ""
echo "📋 Next steps:"
echo "1. Create landing page: sudo nvim /var/www/homelab/index.html"
echo "2. Configure router port forwarding:"
echo "   - Port 80 → 192.168.0.100:80"
echo "   - Port 443 → 192.168.0.100:443"
echo "   - Remove port 3000 forwarding"
echo "3. Test access: http://ak-homelab.duckdns.org/"
echo "4. Set up SSL: sudo certbot --nginx -d ak-homelab.duckdns.org"
echo ""
echo "🔧 Management commands:"
echo "  Test config: sudo nginx -t"
echo "  Reload:      sudo systemctl reload nginx"
echo "  Status:      sudo systemctl status nginx"
