#!/usr/bin/env awk
#
# Returns the top N second-level domains queried (google.com, yahoo.com, ...)
#
# Dependencies:
#   - dnsDecode
#
# Examples:
#   - tawk -e 'topSLD()' file.txt
#   - tawk -e 'topSLD(5)' file.txt

@include "aggr"
@include "bitsanyset"
@include "chomp"
@include "hdr"
@include "_validate_col"

function topSLD(n,        _i, _l, _d) {
    _validate_col("dnsQname")
    if (__PRIHDR__ && hdr()) {
        print $dnsQname, "Flows"
    } else if ($dnsQname ~ /\./ && !bitsanyset($dnsStat, 0x12)) {  # Ignore NBNS and truncated entries
        _l = split(tolower($dnsQname), _d, "\";\"")
        gsub(/^"/, "", _d[1])  # remove leading quote
        gsub(/"$/, "", _d[_l]) # remove trailing quote
        for (_i = 1; _i <= _l; _i++) {
            if (_d[_i] ~ /\.[^\.]{2,}$/) {
                _d[_i] = gensub(/^.+\.([^\.]+\.[^\.]+)$/, "\\1", "g", _d[_i]);
                aggr(chomp(_d[_i]), "flows", n)
            }
        }
    }
}
