#!/bin/sh
# uavpcb-monitor — system health agent (TCP listener)
# VPS connects to 192.168.N.1:LISTEN_PORT and receives a JSON report.
# socat forks uavpcb-monitor-query for each incoming connection.
# Reads router identity from /etc/router.conf (set by setup-router.sh).

# После sysupgrade /etc/router.conf восстанавливается из оверлея с задержкой и
# может ещё отсутствовать на момент START=99. НЕ падаем (иначе procd исчерпает
# respawn-лимит и пометит сервис crash loop — агент останется мёртв до ребута),
# а ждём появления файла. У непривязанного роутера (свежий образ, «Отвязать») ожидание длится
# до привязки — в лог пишем один раз: запись раз в 5 с вытесняла из logread логи агента привязки.
if [ ! -f /etc/router.conf ]; then
    logger -t uavpcb-monitor "waiting for /etc/router.conf..."
    while [ ! -f /etc/router.conf ]; do
        sleep 5
    done
fi

. /lib/functions/uavpcb.sh
uavpcb_load_router_conf /etc/router.conf

LISTEN_PORT="${MONITOR_LISTEN_PORT:-5959}"

logger -t uavpcb-monitor "started TCP listener, router=${ROUTER_NUM} role=${ROLE} port=${LISTEN_PORT}"

# max-children=5: cap concurrent handlers so a misbehaving client cannot
# fork-bomb the router with hanging connections.
exec socat TCP-LISTEN:${LISTEN_PORT},reuseaddr,fork,max-children=5 EXEC:/usr/sbin/uavpcb-monitor-query
