#!/bin/bash
# Update Nginx Configuration with Backend VM IPs
# Run this script on the Nginx proxy VM to update backend configuration

set -euo pipefail

BACKEND_IPS="${1:-}"

if [ -z "$BACKEND_IPS" ]; then
    echo "Usage: $0 <backend-ip1,backend-ip2,...>"
    echo "Example: $0 10.1.1.4,10.2.1.4,10.3.1.4,10.4.1.4,10.5.1.4"
    exit 1
fi

echo "=========================================="
echo "Updating Nginx Backend Configuration"
echo "=========================================="

# Backup current config
sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup.$(date +%Y%m%d_%H%M%S)

# Create upstream configuration
UPSTREAM_RPC=""
UPSTREAM_WS=""

IFS=',' read -ra IPS <<< "$BACKEND_IPS"
for ip in "${IPS[@]}"; do
    ip=$(echo "$ip" | xargs)  # Trim whitespace
    UPSTREAM_RPC="${UPSTREAM_RPC}    server ${ip}:8545 max_fails=3 fail_timeout=30s;\n"
    UPSTREAM_WS="${UPSTREAM_WS}    server ${ip}:8546 max_fails=3 fail_timeout=30s;\n"
done

# Update nginx.conf
sudo sed -i '/upstream besu_rpc_backend {/,/^        }/c\
        upstream besu_rpc_backend {\
          least_conn;\
'"${UPSTREAM_RPC}"'        }' /etc/nginx/nginx.conf

sudo sed -i '/upstream besu_ws_backend {/,/^        }/c\
        upstream besu_ws_backend {\
          least_conn;\
'"${UPSTREAM_WS}"'        }' /etc/nginx/nginx.conf

# Test configuration
echo "Testing Nginx configuration..."
if sudo nginx -t; then
    echo "Configuration is valid. Reloading Nginx..."
    sudo systemctl reload nginx
    echo "Nginx reloaded successfully!"
else
    echo "Configuration test failed. Restoring backup..."
    sudo cp /etc/nginx/nginx.conf.backup.* /etc/nginx/nginx.conf
    exit 1
fi

echo ""
echo "=========================================="
echo "Nginx Backend Configuration Updated!"
echo "=========================================="
echo "Backend IPs configured:"
for ip in "${IPS[@]}"; do
    echo "  - $ip"
done
echo ""
echo "Check Nginx status: sudo systemctl status nginx"
echo "View Nginx logs: sudo tail -f /var/log/nginx/access.log"
echo ""

