"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initSdNotify = initSdNotify;
const node_os_1 = require("node:os");
const logger_1 = __importDefault(require("./logger"));
/**
 * Handle sd_notify protocol, @see https://www.freedesktop.org/software/systemd/man/latest/sd_notify.html
 * No-op if running on unsupported platforms or without Type=notify
 * Soft-fails if improperly setup (this is not necessary for Zigbee2MQTT to function properly)
 */
async function initSdNotify() {
    if (!process.env.NOTIFY_SOCKET) {
        return;
    }
    let socket;
    try {
        const { createSocket } = await import("unix-dgram");
        socket = createSocket("unix_dgram");
    }
    catch (error) {
        if ((0, node_os_1.platform)() !== "win32" || process.env.WSL_DISTRO_NAME) {
            // not on plain Windows
            logger_1.default.error(`Could not init sd_notify: ${error.message}`);
            // biome-ignore lint/style/noNonNullAssertion: always Error
            logger_1.default.debug(error.stack);
        }
        else {
            // this should not happen
            logger_1.default.warning(`NOTIFY_SOCKET env is set: ${error.message}`);
        }
        return;
    }
    const sendToSystemd = (msg) => {
        const buffer = Buffer.from(msg);
        // biome-ignore lint/style/noNonNullAssertion: valid from start of function
        socket.send(buffer, 0, buffer.byteLength, process.env.NOTIFY_SOCKET, (err) => {
            if (err) {
                logger_1.default.warning(`Failed to send "${msg}" to systemd: ${err.message}`);
            }
        });
    };
    const notifyStopping = () => sendToSystemd("STOPPING=1");
    sendToSystemd("READY=1");
    const wdUSec = process.env.WATCHDOG_USEC !== undefined ? Math.max(0, Number.parseInt(process.env.WATCHDOG_USEC, 10)) : -1;
    if (wdUSec > 0) {
        // Convert us to ms, send twice as frequently as the timeout
        const watchdogInterval = setInterval(() => sendToSystemd("WATCHDOG=1"), wdUSec / 1000 / 2);
        return {
            notifyStopping,
            stop: () => clearInterval(watchdogInterval),
        };
    }
    if (wdUSec !== -1) {
        logger_1.default.warning(`WATCHDOG_USEC invalid: "${process.env.WATCHDOG_USEC}", parsed to "${wdUSec}"`);
    }
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