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

USE_PROCD=1
START=96    # после main-modem/aux-modem (START=95)
STOP=10

start_service() {
	local enabled
	config_load modem-man
	# проверяем есть ли хоть один включённый модем с watchdog
	local any_enabled=0
	check_enabled() {
		local cfg="$1" en wd
		config_get en "$cfg" enabled "0"
		config_get wd "$cfg" watchdog "1"
		[ "$en" = "1" ] && [ "$wd" = "1" ] && any_enabled=1
	}
	config_foreach check_enabled modem
	[ "$any_enabled" = "1" ] || return 0

	procd_open_instance
	procd_set_param command /usr/bin/modem-man
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param respawn 60 5 0
	procd_close_instance
}

stop_service() {
	# Signal watch_one subshells to exit gracefully.
	# procd only kills the main process; the background loops check this flag.
	touch /var/run/modem-man/stop
	sleep 2
	rm -f /var/run/modem-man/stop
	# Clean up stale hotplug flags so the next start doesn't inherit them.
	# hotplug_<iface> causes a 60s watchdog stall; hotplug_<iface>_down
	# suppresses the add-handler on the next device reconnect.
	rm -f /var/run/modem-man/hotplug_*
}

service_triggers() {
	procd_add_reload_trigger "modem-man"
}
