#!/bin/sh
set -eu
umask 077
IFS= read -r accessKey < "${POST76_EXPORTER_KEY_FILE:-/run/secrets/metrics_access_key}" || [ -n "$accessKey" ]
case "$accessKey" in *[!a-f0-9]*|"") echo "Invalid metrics access key." >&2; exit 1;; esac
[ "${#accessKey}" -eq 64 ] || { echo "Invalid metrics access key." >&2; exit 1; }
cat > /run/post76/nginx.conf <<EOF
pid /run/post76/nginx.pid;
error_log /dev/stderr warn;
events { worker_connections 64; }
http {
    access_log off;
    client_body_temp_path /run/post76/client_temp;
    proxy_temp_path /run/post76/proxy_temp;
    fastcgi_temp_path /run/post76/fastcgi_temp;
    uwsgi_temp_path /run/post76/uwsgi_temp;
    scgi_temp_path /run/post76/scgi_temp;
    map \$http_authorization \$authorized { default 0; "Bearer $accessKey" 1; }
    server {
        listen 8080;
        server_name _;
        location = /health { return 200 "ok\n"; }
        location = /metrics {
            if (\$authorized = 0) { return 401; }
            limit_except GET { deny all; }
            alias /metrics/metrics.prom;
            default_type "text/plain; version=0.0.4";
            add_header Cache-Control "no-store" always;
        }
        location / { return 404; }
    }
}
EOF
if [ "${1:-}" = "--test" ]; then
    exec nginx -t -c /run/post76/nginx.conf
fi
exec nginx -c /run/post76/nginx.conf -g "daemon off;"
