#!/usr/bin/env awk
#
# Split the input file into smaller more manageable files.
#
# The files to create can be specified as argument to the function (one comma
# separated string).
#
# If no argument is specified, creates one file per column whose name ends
# with Stat, e.g., dnsStat, and one for pwxType (pw) and
# covertChannels (cc)
#
# Valid arguments are:
#   - arp        - bgp        - dhcp        - dns        - ftp        - http
#   - icmp       - igmp       - irc         - modbus     - nat        - ntp
#   - ospf       - pop        - radius      - sctp       - smb        - smtp
#   - ss         - stp        - syslog      - tftp       - voip       - vrrp
#
#   - pw (cleartext passwords)
#   - cc (covert channels)
#
# Parameters:
#   - s: a comma separated list of files to create.
#
# Dependencies:
#   - None
#
# Examples:
#   - tawk 'ffsplit()' file.txt
#   - tawk 'ffsplit("dns")' file.txt
#   - tawk 'ffsplit("cc,dns,http")' file.txt

@include "COL"
@include "hdr"
@include "printerr"
@include "_validate_col"

function ffsplit(s,        _i, _n, _prefix, _suffix, _tmp) {
    if (!__FFNAME__[1]) {
        _prefix = gensub(/\.txt$/, "", 1, FILENAME)
        if (s) {
            _n = split(s, _suffix, ",")
        } else {
            for (_i = 1; _i <= NF; _i++) {
                if (COL[_i] == "covertChannels") _suffix[++_n] = "cc"
                else if (COL[_i] == "pwxType") _suffix[++_n] = "pw"
                else if (COL[_i] == "flowStat"   || COL[_i] == "geoStat"     ||
                         COL[_i] == "smbHdrStat" || COL[_i] == "smbNHdrStat" ||
                         COL[_i] == "tcpFStat"   || COL[_i] == "tp0fStat")
                {
                    continue
                } else if (match(COL[_i], /^(.+)Stat$/, _tmp)) {
                    _suffix[++_n] = _tmp[1]
                }
            }
            if (!_n) {
                printerr("ffsplit: no usable column found")
                exit 1
            }
        }
        for (_i = 1; _i <= _n; _i++) {
            __FFNAME__[_i] = _prefix "_" _suffix[_i] ".txt"
            if (_suffix[_i] == "cc") __FFIELD__[_i] = "covertChannels"
            else if (_suffix[_i] == "pw") __FFIELD__[_i] = "pwxType"
            else __FFIELD__[_i] = _suffix[_i] "Stat"
            _validate_col(__FFIELD__[_i])
        }
    }

    _n = length(__FFNAME__)

    for (_i = 1; _i <= _n; _i++) {
        if (strtonum($COL[__FFIELD__[_i]]) || hdr()) {
            print >> __FFNAME__[_i]
        }
    }
}
