#!/usr/bin/env awk
#
# Sorts the file according to 'col'.
# Multiple column numbers can be specified by using ';' as separator, e.g., 1 ";" 2.
#
# To sort in reverse order, use the 't2rsort()' function or set 'rev' to 1.
#
# If 'num' is omitted or 0, 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 -g) [default]
#
# Parameters:
#   - col   : column number(s) to use for the sorting
#             (use ';' as separator to sort by multiple columns)
#   - [num] : return the top/bottom 'num' results
#   - [type]: type of sorting to do ('ip', 'str', 'num')
#   - [rev] : sort in reverse order
#
# Dependencies:
#   - None
#
# See Also:
#   - t2rsort
#
# Examples:
#   - tawk 't2sort(1)' file.txt
#   - tawk 't2sort(duration)' file.txt
#   - tawk 't2sort(numBytesSnt, 5)' file.txt
#   - tawk 't2sort(srcIP, 0, "ip")' file.txt
#   - tawk 't2sort(dstIP, 0, "ip", 1)' file.txt
#   - tawk 't2sort(flowInd ";" pktNo)' file_packets.txt

@include "hdr"
@include "isipstr"
@include "isnum"

function t2sort(col, num, type, rev,        _i, _n, _cols, _revs, _sortorder, _sorttype, _types) {
    if (hdr()) {
        __SORTHDR__ = $0
    } else {
        if (length(__SORTCMD__) == 0) {
            if (rev) _sortorder = "r" # reverse sort
            if (col == 0) {
                printerr("t2sort: a column number != 0 MUST be specified")
                exit(1)
            } else if (col ~ /[1-9][0-9]*\(;[1-9][0-9]*\)*/) {
                printerr("t2sort: invalid column number '" col "'")
                exit(1)
            }
            if (num < 0) {
                __SORTNUM__ = -num
            } else {
                __SORTNUM__ = num
            }
            __SORTCMD__ = "LC_ALL=C sort -t'"OFS"'"
            _n = split(col, _cols, /;/)
            _m = split(type, _types, /;/)
            if (_m < _n) {
                for (_i = _m; _i <= _n; _i++) {
                    _types[_i] = _types[1]
                }
            }
            _m = split(rev, _revs, /;/)
            if (_m < _n) {
                for (_i = _m; _i <= _n; _i++) {
                    _revs[_i] = _revs[1]
                }
            }
            # TODO split types as well
            # TODO split orders as well
            for (_i = 1; _i <= _n; _i++) {
                # If no type provided, try to guess the type
                if (!_types[_i]) {
                    if (isipstr($_cols[_i])) _types[_i] = "ip"
                    else if (isnum($_cols[_i])) _types[_i] = "num"
                    else _types[_i] = "str"
                }
                switch (tolower(_types[_i])) {
                    case "ip":
                        _sorttype = "V"
                        break
                    case "str":
                        _sorttype = ""
                        break
                    case "num":
                    default:
                        _sorttype = "g"
                        break
                }
                if (num < 0) {
                    if (_revs[_i]) _sortorder = "r"
                    else _sortorder = ""
                } else {
                    if (_revs[_i]) _sortorder = ""
                    else _sortorder = "r"
                }
                __SORTCMD__ = __SORTCMD__ " -" _sorttype "" _sortorder "k" _cols[_i] "," _cols[_i]
            }
        }
        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 (__PRIHDR__ && __SORTHDR__) print __SORTHDR__
    while ((__SORTNUM__ == 0 || _linenum < __SORTNUM__) && (__SORTCMD__ |& getline _line) > 0) {
        print _line
        _linenum++
    }
    close(__SORTCMD__)
    __SORTCMD__ = ""
    __SORTHDR__ = ""
}

END {
    if (__SORTCMD__) {
        _prisort()
    }
}
