#!/bin/sh /etc/rc.common
# nDPIsrvd init script for OpenWrt
# Event distribution broker for nDPId
# Copyright (C) 2025 CyberMind.fr

START=50
STOP=11
USE_PROCD=1

PROG=/usr/sbin/ndpisrvd
CONF=/etc/config/ndpid
RUNTIME_DIR=/var/run/ndpid

start_service() {
	local enabled listen_socket tcp_port tcp_address max_clients
	local collector_socket

	config_load ndpid

	# Check distributor settings
	config_get_bool enabled distributor enabled 1
	[ "$enabled" -eq 0 ] && {
		logger -t ndpisrvd "Service disabled in config"
		return 0
	}

	# Create runtime directory
	mkdir -p "$RUNTIME_DIR"
	chown nobody:nogroup "$RUNTIME_DIR"

	# Get configuration
	config_get collector_socket main collector_socket /var/run/ndpid/collector.sock
	config_get listen_socket distributor listen_socket /var/run/ndpid/distributor.sock
	config_get tcp_port distributor tcp_port 7000
	config_get tcp_address distributor tcp_address 127.0.0.1
	config_get max_clients distributor max_clients 10

	logger -t ndpisrvd "Starting nDPIsrvd (collector: $collector_socket, distributor: $listen_socket)"

	# Build command
	local cmd_args="-c $collector_socket -s $listen_socket"

	# Add TCP listener if enabled
	[ "$tcp_port" -gt 0 ] && {
		cmd_args="$cmd_args -S ${tcp_address}:${tcp_port}"
	}

	procd_open_instance ndpisrvd
	procd_set_param command "$PROG" $cmd_args
	procd_set_param respawn ${respawn_threshold:-3600} ${respawn_timeout:-5} ${respawn_retry:-5}
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param pidfile /var/run/ndpisrvd.pid
	procd_close_instance
}

stop_service() {
	logger -t ndpisrvd "Stopping nDPIsrvd"
}

reload_service() {
	stop
	start
}

service_triggers() {
	procd_add_reload_trigger "ndpid"
}
