#!/usr/bin/env bash
# Splice the SDP dashboard location into the existing nginx default site on
# 172.18.139.186. Idempotent: re-running won't duplicate the block.
#
# We don't replace the file — we insert before the closing `}` of the
# existing `server { ... }` block. The block is guarded by a sentinel
# comment so subsequent runs are no-ops.

set -euo pipefail
cd "$(dirname "$0")/.."

HOST_186="${SDP_186_HOST:-administrator@172.18.139.186}"
PASS_186="${SDP_186_PASS:-Bre@kthrough2312}"

if ! command -v sshpass >/dev/null 2>&1; then
  echo "sshpass not found. Install with: brew install sshpass" >&2
  exit 1
fi

SSH="sshpass -p $PASS_186 ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR"

NGINX_SITE=/etc/nginx/sites-available/default
SDP_MARKER='# >>> sdp >>>'

$SSH "$HOST_186" bash -s <<REMOTE
set -e
NGINX_SITE=$NGINX_SITE
SDP_MARKER='$SDP_MARKER'

if grep -qF "\$SDP_MARKER" "\$NGINX_SITE"; then
  echo "sdp block already present, skipping"
  exit 0
fi

cp "\$NGINX_SITE" "\$NGINX_SITE.bak.\$(date +%s)"

python3 - <<'PY'
import re
path = "/etc/nginx/sites-available/default"
src = open(path).read()
block = """
\t# >>> sdp >>>
\t# Sandbox Deployment Platform dashboard
\tlocation /api/ {
\t\tproxy_pass http://127.0.0.1:8080;
\t\tproxy_set_header Host $host;
\t\tproxy_set_header X-Real-IP $remote_addr;
\t\tproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
\t}

\tlocation /ws/ {
\t\tproxy_pass http://127.0.0.1:8080;
\t\tproxy_http_version 1.1;
\t\tproxy_set_header Upgrade $http_upgrade;
\t\tproxy_set_header Connection "upgrade";
\t\tproxy_read_timeout 3600s;
\t\tproxy_send_timeout 3600s;
\t}

\tlocation / {
\t\troot /home/administrator/SDP/dashboard;
\t\tindex index.html;
\t\ttry_files \$uri \$uri/ \$uri.html /index.html;
\t}
\t# <<< sdp <<<
"""

def find_server_end(s):
    i = s.find("server")
    if i < 0: return -1
    j = s.find("{", i)
    if j < 0: return -1
    depth = 1
    k = j + 1
    in_str = None
    while k < len(s):
        c = s[k]
        if in_str:
            if c == in_str and s[k-1] != "\\":
                in_str = None
        else:
            if c in ('"', "'"):
                in_str = c
            elif c == "{":
                depth += 1
            elif c == "}":
                depth -= 1
                if depth == 0:
                    return k
        k += 1
    return -1

end = find_server_end(src)
if end < 0:
    raise SystemExit("could not find server block end")

new = src[:end] + block + src[end:]
open(path, "w").write(new)
PY

nginx -t
systemctl reload nginx
echo "nginx patched and reloaded"
REMOTE
