#!/usr/bin/env awk
#
# Performs aggregation of 'fields' and store 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 : tab separated list of fields to aggregate
#   - [val]  : tab separated list of values to aggregate [default: "flows"]
#   - [num]  : number of records to return [default: all]
#
# Dependencies:
#   - None
#
# See Also:
#   - aggrrep
#
# Examples:
#   - tawk 'aggr($httpUsrAg)' file.txt
#   - tawk 'shost("1.2.3.4") && !dnet("1.2.3.0/24") {
#         aggr($DstIP4, $numBytesSnt)
#     }' file.txt
#   - tawk 'snet("1.2.3.4/24") && !dnet("1.2.3.0/24") {
#         aggr($SrcIP4 "\t" $DstIP4, $numBytesSnt)
#     }' file.txt
#   - tawk 'snet("1.2.3.4/24") && !dnet("1.2.3.0/24") {
#         aggr(tuple2(), "Flows", 5)
#     }' file.txt
#   - tawk 'snet("1.2.3.4/24") && !dnet("1.2.3.0/24") {
#         aggr(tuple2() "\t" $L4Proto, $numPktsSnt "\t" $numBytesSnt "\t" "Flows")
#     }' file.txt

@include "hdr"
@include "max"
@include "streqi"
@include "strisempty"

function aggr(fields, val, num,        _i, _f, _l, _vval) {
    if (strisempty(val)) val = "Flows"
    if (num < 0) {
        AGGRNUM = -num
    } else {
        AGGRNUM = num
        AGGRORDER = "r" # reverse sort
    }
    if (hdr()) {
        AGGRHDR = fields "\t" val
    } else {
        _l = split(val, _vval, "\t")
        split(AGGR[fields], _f, "\t")
        for (_i = 1; _i <= _l; _i++) {
            if (streqi(_vval[_i], "flows")) {
                _vval[_i] = 1
            }
            _f[_i] += _vval[_i]
        }
        # Rebuild val
        val = _f[1]
        for (_i = 2; _i <= _l; _i++) {
            val = val "\t" _f[_i]
        }
        AGGR[fields] = val
    }
}

# Print the result of the aggr() function
# (see END block at the end of this file)
function _priaggr(        _k, _key, _idx, _aggrcmd, _line, _linenum) {
    for (_key in AGGR) {
        if (length(_aggrcmd) == 0) {
            _idx = max(2, split(_key, _k, "\t")+1)
            _aggrcmd = "sort -t'\t' -n" AGGRORDER "k" _idx
        }
        print _key "\t" AGGR[_key] |& _aggrcmd
    }
    close(_aggrcmd, "to")
    if (AGGRHDR) print AGGRHDR
    while ((AGGRNUM == 0 || _linenum < AGGRNUM) && (_aggrcmd |& getline _line) > 0) {
        print _line
        _linenum++
    }
    close(_aggrcmd)
    AGGRHDR = ""
    # AGGR = ""
}

END {
    if (length(AGGR) > 0) {
        _priaggr()
    }
}
