#!/usr/bin/env awk
#
# Performs aggregation of repetitive values and stores the sum of val.
# If val is omitted or equal to "Flows" (case insensitive),
# counts the number of flows.
# If num is omitted, returns the full list, otherwise the top (num > 0) or
# bottom (num < 0) num results
# Results are sorted according to the first value of val.
#
# Parameters:
#   - fields : the repetitive value to aggregate
#   - [val]  : tab separated list of values to aggregate [default: "flows"]
#   - [num]  : number of records to return [default: all]
#
# Dependencies:
#   - None
#
# See Also:
#   - aggr
#
# Examples:
#   - tawk 'aggrrep($httpUsrAg)' file.txt
#   - tawk 'shost("1.2.3.4") && !dnet("1.2.3.0/24") {
#         aggrrep($dnsAName)
#     }' file.txt
#   - tawk 'shost("1.2.3.4") && !dnet("1.2.3.0/24") {
#         aggrrep($dnsAName, $numPktsSnt)
#     }' file.txt
#   - tawk 'shost("1.2.3.4") && !dnet("1.2.3.0/24") {
#         aggrrep($dnsAName, $numBytesSnt "\t" "Flows")
#     }' file.txt

@include "aggr"

function aggrrep(fields, val, num,        _i, _f, _l, _sep) {
    if (fields ~ /^".*"$/) _sep = "\";\""
    else _sep = ";"
    _l = split(fields, _f, _sep)
    gsub(/^"/, "", _f[1])  # remove leading quote
    gsub(/"$/, "", _f[_l]) # remove trailing quote
    for (_i = 1; _i <= _l; _i++) {
        if (length(_f[_i])) {
            aggr(_f[_i], val, num)
        }
    }
}
