#!/usr/bin/env bash
set -euo pipefail

APP_DIR="$(readlink -f "$(dirname "${BASH_SOURCE[0]}")/..")"
APP_DATA_DIR="${APP_DIR}/data"

NGINX_CONFIG_DIR="${APP_DATA_DIR}/nginx"
NGINX_CONFIG_FILE="${NGINX_CONFIG_DIR}/default.conf"
MOSQUITTO_CONFIG_FILE="${APP_DATA_DIR}/config/mosquitto.conf"

NGINX_MARKER_REGEX='^# Umbrel Mosquitto canonical nginx.conf 17-Mar-2026$'
LEGACY_HTTP_DIR_LINE='http_dir /mosquitto/www'

mkdir -p "${NGINX_CONFIG_DIR}"

if [[ ! -f "${NGINX_CONFIG_FILE}" ]] || ! grep -qx "${NGINX_MARKER_REGEX}" "${NGINX_CONFIG_FILE}"; then
  echo "Updating nginx configuration file for Mosquitto."
  cat >"${NGINX_CONFIG_FILE}" <<'EOF'
# Umbrel Mosquitto canonical nginx.conf 17-Mar-2026
map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}

map $http_upgrade $upgrade_request {
    default 1;
    '' 0;
}

server {
    listen 80;
    server_name _;
    root /usr/share/nginx/html;
    index index.html;

    location / {
        error_page 418 = @websocket;

        if ($upgrade_request = 1) {
            return 418;
        }

        try_files $uri $uri/ /index.html;
    }

    location @websocket {
        proxy_pass http://broker:9001;
        proxy_http_version 1.1;
        proxy_read_timeout 1d;
        proxy_send_timeout 1d;
        proxy_set_header Host $host;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }
}
EOF
fi

if [[ -f "${MOSQUITTO_CONFIG_FILE}" ]] && grep -qxF "${LEGACY_HTTP_DIR_LINE}" "${MOSQUITTO_CONFIG_FILE}"; then
  echo "Removing legacy http_dir configuration from mosquitto.conf."
  sed -i '\|^http_dir /mosquitto/www$|d' "${MOSQUITTO_CONFIG_FILE}"
fi
