#!/bin/bash
# Host Setup Script for Quant Engine (.NET 10 & Nginx)
# Must be executed with sudo privileges

set -e

NGINX_CONF="/etc/nginx/sites-available/gitea-ip.conf"
SERVICE_FILE="/etc/systemd/system/quantengine.service"
APP_ENV_FILE="/home/kjh2064/.config/quantengine.env"

echo "========================================="
echo "Configuring Host Infrastructure Services"
echo "========================================="

# 1. Update Nginx Site Config
if [ -f "$NGINX_CONF" ]; then
    if ! grep -q "location /quant/" "$NGINX_CONF"; then
        echo "Injecting /quant/ proxy pass block into Nginx..."
        python3 -c "
p = '$NGINX_CONF'
c = open(p).read()
sub = '''    # Blazor Web App (Quant Engine)
    location /quant/ {
        proxy_pass http://127.0.0.1:5000/;
        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_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

'''
c = c.replace('location / {', sub + '    location / {')
open(p, 'w').write(c)
"
    else
        echo "Nginx /quant/ block already exists."
    fi
else
    echo "ERROR: Nginx conf not found at $NGINX_CONF"
    exit 1
fi

# 2. Write Systemd Service File
echo "Writing systemd service file..."
cat > "$SERVICE_FILE" << 'EOF'
[Unit]
Description=Quant Engine Blazor Admin Web App (.NET 10)
After=network.target

[Service]
WorkingDirectory=/home/kjh2064/quantengine_active
ExecStart=/usr/bin/dotnet /home/kjh2064/quantengine_active/QuantEngine.Web.dll
Restart=always
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=quantengine
User=kjh2064
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=ASPNETCORE_URLS=http://127.0.0.1:5000
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
EnvironmentFile=-/home/kjh2064/.config/quantengine.env

[Install]
WantedBy=multi-user.target
EOF

# 3. Reload Daemons
echo "Reloading systemd daemon..."
systemctl daemon-reload
systemctl enable quantengine

# 4. Run Deploy Script to populate active directory
echo "Executing deployment script..."
chmod +x /home/kjh2064/tmp/deploy.sh
bash /home/kjh2064/tmp/deploy.sh

# 5. Reload Nginx
echo "Testing Nginx config and reloading..."
nginx -t
systemctl reload nginx

echo "========================================="
echo "Host Configuration Successful!"
echo "========================================="
