#!/usr/bin/env awk
#
# Sorts the file according to 'col'
#
# If num is omitted, returns the full list, otherwise the top (num > 0) or
# bottom (num < 0) num results
#
# The type of sorting to do (numeric, IP (version) or string) is determined
# based on the first matching record. If the field is empty, then numeric sort
# will be used. The type can be forced by specifiying the 'type' parameter as
# follows:
#   - "ip" : sorts IP addresses or version (sort -V)
#   - "str": sorts strings
#   - "num": sorts numbers (sort -n) [default]
#
# Dependencies:
#   - None
#
# Examples:
#   - tawk '{ t2sort(1) }' file.txt
#   - tawk '{ t2sort(Duration) }' file.txt
#   - tawk '{ t2sort(numBytesSnt, 5) }' file.txt
#   - tawk '{ t2sort(SrcIP4, 0, "ip") }' file.txt

@include "hdr"

function t2sort(col, num, type,       _sortorder, _sorttype) {
    if (hdr()) {
        SORTHDR = $0
    } else {
        if (length(SORTCMD) == 0) {
            if (num < 0) {
                SORTNUM = -num
            } else {
                SORTNUM = num
                _sortorder = "r" # reverse sort
            }
            # If no type provided, try to guess the type
            if (!type) {
                if ($col ~ /^[0-9]{1,3}(\.[0-9]{1,3}){3}$/) type = "ip"
                else if ($col ~ /^[0-9](\.[0-9]*)?$/) type = "num"
                else type = "str"
            }
            switch (tolower(type)) {
                case "ip":
                    _sorttype = "V"
                    break
                case "str":
                    _sorttype = ""
                    break
                case "num":
                default:
                    _sorttype = "n"
                    break
            }
            SORTCMD = "sort -t'\t' -" _sorttype "" _sortorder "k" col
        }
        print |& SORTCMD
    }
}

# Print the result of the t2sort() function
# (see END block at the end of this file)
function _prisort(        _line, _linenum) {
    close(SORTCMD, "to")
    if (SORTHDR) print SORTHDR
    while ((SORTNUM == 0 || _linenum < SORTNUM) && (SORTCMD |& getline _line) > 0) {
        print _line
        _linenum++
    }
    close(SORTCMD)
    SORTCMD = ""
    SORTHDR = ""
}

END {
    if (SORTCMD) {
        _prisort()
    }
}
