#!/bin/bash
# Setup nginx reverse proxy for both dashboards - ACTUALLY WORKS
set -e

echo "Setting up nginx for both dashboards..."

# Add to /etc/hosts
if ! grep -q "aphoria.local" /etc/hosts 2>/dev/null; then
    echo "127.0.0.1 stemedb.local aphoria.local api.local" | sudo tee -a /etc/hosts
fi

# Aphoria Dashboard
sudo tee /etc/nginx/sites-available/aphoria-dashboard > /dev/null <<'EOF'
server {
    listen 80;
    server_name aphoria.local;
    location / {
        proxy_pass http://127.0.0.1:18189;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_read_timeout 300s;
        proxy_connect_timeout 300s;
        proxy_send_timeout 300s;
    }
}
EOF

# StemeDB Dashboard
sudo tee /etc/nginx/sites-available/stemedb-dashboard > /dev/null <<'EOF'
server {
    listen 80;
    server_name stemedb.local;
    location / {
        proxy_pass http://127.0.0.1:18188;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}
EOF

# API
sudo tee /etc/nginx/sites-available/stemedb-api > /dev/null <<'EOF'
server {
    listen 80;
    server_name api.local;
    location / {
        proxy_pass http://127.0.0.1:18180;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_read_timeout 300s;
        proxy_connect_timeout 300s;
        proxy_send_timeout 300s;
    }
}
EOF

# Enable sites
sudo ln -sf /etc/nginx/sites-available/aphoria-dashboard /etc/nginx/sites-enabled/
sudo ln -sf /etc/nginx/sites-available/stemedb-dashboard /etc/nginx/sites-enabled/
sudo ln -sf /etc/nginx/sites-available/stemedb-api /etc/nginx/sites-enabled/

# Remove old broken config
sudo rm -f /etc/nginx/sites-enabled/stemedb

# Test and reload
sudo nginx -t && sudo systemctl reload nginx

echo ""
echo "✅ Done!"
echo ""
echo "Access:"
echo "  http://aphoria.local  - Aphoria Dashboard"
echo "  http://stemedb.local  - StemeDB Dashboard"
echo "  http://api.local      - Backend API"
