#!/bin/sh
# Runs at install time (as root). Publishes the agent same-origin under DSM's own
# port via an nginx location (^~ so it wins over DSM's /api regex), so the login
# opens as a window INSIDE the DSM desktop instead of a separate ip:port tab.
CONF=/usr/local/etc/nginx/conf.d/dsm.phoenix.conf
cat > "$CONF" <<'NGINX'
location ^~ /phoenix/ {
    proxy_pass http://127.0.0.1:8752/;
    proxy_http_version 1.1;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_read_timeout 3600s;
}
NGINX
# Reload DSM's nginx to pick up the new location (best-effort across DSM variants).
# NOTE: DSM 7 runs this as the (unprivileged) package user, so writing to nginx
# usually fails — the reverse proxy is installed as root by scripts/release-all.sh
# (or a one-time manual command). This block only succeeds on root-run installs.
nginx -s reload 2>/dev/null || synosystemctl reload nginx 2>/dev/null || synoservicecfg --reload nginx 2>/dev/null || true
exit 0
