#!/bin/sh
# Netifyd Data Collector
# Collects statistics from netifyd and creates status.json
# Copyright (C) 2025 CyberMind.fr

NETIFYD_STATUS="/var/run/netifyd/status.json"
TMP_FILE="/tmp/netifyd-status.tmp"
FLOW_DUMP="/tmp/netifyd-flow-dump.json"

# Create run directory if needed
mkdir -p /var/run/netifyd

# Check if netifyd is running
if ! pidof netifyd >/dev/null 2>&1; then
	echo '{"error":"netifyd not running","flow_count":0,"devices":{},"dhc_size":0}' > "$NETIFYD_STATUS"
	exit 1
fi

# Get status from netifyd CLI
STATUS_OUTPUT=$(netifyd -s 2>/dev/null)

# Parse flow count from status
FLOW_COUNT=$(echo "$STATUS_OUTPUT" | grep -i "flows:" | head -1 | awk '{print $2}' | tr -d ',' || echo 0)

# Parse detection stats from status output
# Example lines:
#   Detection Cache Entries: 156
#   Detected Applications: 24
#   Detected Protocols: 12
DHC_SIZE=$(echo "$STATUS_OUTPUT" | grep -i "cache entries\|applications" | head -1 | awk '{print $NF}' | tr -d ',' || echo 0)
PROTO_COUNT=$(echo "$STATUS_OUTPUT" | grep -i "protocols:" | awk '{print $NF}' | tr -d ',' || echo 0)

# Try to extract device count from ARP table as fallback
DEVICE_COUNT=$(ip neigh show | grep -c "REACHABLE\|STALE\|DELAY" 2>/dev/null || echo 0)

# Build minimal devices object (MAC -> IP mapping from ARP)
if command -v jq >/dev/null 2>&1; then
	DEVICES_OBJ=$(ip neigh show 2>/dev/null | awk '$5 != "" && $1 != "" {print "{\"mac\":\""$5"\",\"ip\":\""$1"\"}"}' | jq -s 'reduce .[] as $item ({}; .[$item.mac] += [$item.ip])' 2>/dev/null || echo '{}')
else
	DEVICES_OBJ='{}'
fi

# Estimate total bytes from interface stats
TOTAL_BYTES=0
for iface in br-lan eth0 eth1 wlan0; do
	if [ -d "/sys/class/net/$iface" ]; then
		RX=$(cat /sys/class/net/$iface/statistics/rx_bytes 2>/dev/null || echo 0)
		TX=$(cat /sys/class/net/$iface/statistics/tx_bytes 2>/dev/null || echo 0)
		TOTAL_BYTES=$((TOTAL_BYTES + RX + TX))
	fi
done

# Create JSON status file
cat > "$TMP_FILE" <<EOF
{
	"flow_count": ${FLOW_COUNT:-0},
	"devices": ${DEVICES_OBJ},
	"dhc_size": ${DHC_SIZE:-0},
	"protocol_count": ${PROTO_COUNT:-0},
	"total_bytes": ${TOTAL_BYTES:-0},
	"device_count": ${DEVICE_COUNT:-0},
	"timestamp": $(date +%s),
	"uptime": $(awk '{print int($1)}' /proc/uptime 2>/dev/null || echo 0)
}
EOF

# Atomic move to prevent partial reads
mv "$TMP_FILE" "$NETIFYD_STATUS"

exit 0
