#!/bin/sh /etc/rc.common

#
# Copyright (C) 2026 Nethesis S.r.l.
# SPDX-License-Identifier: GPL-2.0-only
#

START=95
STOP=5
USE_PROCD=1

PROG="/usr/bin/vmalert"
RULE_DIR="/etc/vmalert/rules"

start_service() {
    config_load vmalert 2>/dev/null || true
    
    local datasource_url http_listen_addr
    config_get datasource_url main datasource_url "http://localhost:8428"
    config_get http_listen_addr main http_listen_addr "127.0.0.1:8081"
    
    # Forward alerts to the new my.nethesis.it during the migration window,
    # mirroring send-heartbeat / send-inventory: enterprise systems POST to the
    # credential-translation proxy at my.nethesis.it/proxy/alerts using the
    # ns-plug credentials (system_id:secret), which the proxy maps to the new my
    # credentials. vmalert appends /api/v2/alerts to the notifier URL. The my
    # switch-off release will repoint this to the native collect path.
    local system_id system_secret system_type alerts_disabled notifier_url notifier_user notifier_pass
    config_load ns-plug 2>/dev/null && {
        config_get system_id config system_id ""
        config_get system_secret config secret ""
        config_get system_type config type ""
        # opt-out: set ns-plug.config.disable_my_alerts=1 for alert-proxy only mode
        config_get_bool alerts_disabled config disable_my_alerts 0
    }

    if [ "$system_type" = "enterprise" ] && [ -n "$system_id" ] && [ -n "$system_secret" ] && [ "$alerts_disabled" = "0" ]; then
        notifier_url="https://my.nethesis.it/proxy/alerts"
        notifier_user="$system_id"
        notifier_pass="$system_secret"
    else
        notifier_url=""
    fi
    
    procd_open_instance
    procd_set_param command $PROG
    procd_append_param command -rule="$RULE_DIR/*.yaml"
    procd_append_param command -httpListenAddr="$http_listen_addr"
    procd_append_param command -datasource.url="$datasource_url"
    procd_append_param command -remoteRead.url="$datasource_url"
    procd_append_param command -remoteWrite.url="$datasource_url"
    procd_append_param command -evaluationInterval=30s
    
    # Always notify the local alert-proxy (handles unregistered machines gracefully)
    procd_append_param command -notifier.url="http://127.0.0.1:9095"

    # Also forward alerts to my.nethesis.it for registered enterprise systems
    if [ -n "$notifier_url" ]; then
        procd_append_param command -notifier.url="$notifier_url"
        procd_append_param command -notifier.basicAuth.username="$notifier_user"
        procd_append_param command -notifier.basicAuth.password="$notifier_pass"
    fi
    
    procd_set_param stdout 1
    procd_set_param stderr 1
    procd_set_param respawn 3600 5 5
    procd_close_instance
}

reload_service() {
    stop
    start
}

service_triggers() {
    procd_add_reload_trigger vmalert ns-plug
}
