#!/usr/bin/env awk
#
# Returns the top N top-level domains (TLD) queried (.com, .net, ...)
#
# Parameters:
#   - n: number of rows to return (0: all, n > 0: top n, n < 0: bottom n)
#
# Dependencies:
#   - dnsDecode
#
# Examples:
#   - tawk 'topTLD()' file.txt
#   - tawk 'topTLD(5)' file.txt

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

function topTLD(n,        _i, _l, _d) {
    _validate_col(dnsQname, "dnsQname")
    if (!hdr() && $dnsQname ~ /\./) {
        _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] !~ /^_ldap\._/) { # TODO ignore case and truncated entries
                gsub(/^.+\./, "", _d[_i]);
                if (_d[_i] !~ /\.[0-9]+$/) { # No numbers in TLDs
                    aggr(chomp(_d[_i]), "flows", n)
                }
            }
        }
    }
}
