#!/bin/bash

# 检查 conntrack 命令是否可用
if ! command -v conntrack &>/dev/null; then
    echo '[{"value":0,"tags":"conntrack_not_found"}]'
    exit 0
fi

# 合并两个流处理结果（ipv4 和 ipv6），通过 bash process substitution
awk '
{
    key = $1 "_" $2
    count[key]++
}
END {
    first = 1
    printf "["
    for (k in count) {
        if (!first) {
            printf ","
        }
        printf "{\"value\":%d,\"tags\":\"%s\"}", count[k], k
        first = 0
    }
    printf "]\n"
}' < <(
    # Stream IPv4
    conntrack -L -f ipv4 2>/dev/null | awk '{print "ipv4", $1}' ;
    # Stream IPv6
    conntrack -L -f ipv6 2>/dev/null | awk '{print "ipv6", $1}' ;
)
