#!/bin/bash
#
# Generates a PDF/LaTeX report out of a PCAP or flow file.
#
# Usage: t2fm [OPTION...] <FILE>
#
# Required plugins:
#   basicFlow
#   basicStats
#   txtSink
#
# Optional plugins:
#   arpDecode
#   dnsDecode
#   #geoip
#   httpSniffer     (HTTP_SAVE_*=1)
#   nDPI            (NDPI_OUTPUT_STR=1)
#   portClassifier  (PBC_NUM=1 &&/|| PBC_STR=1)
#   pwX
#   ssDecode/sshDecode
#
# TODO
#   - check for pdflatex (_check_dependencies_*)
#   - Add elapsed time
#   - add link to virustotal for exe
#   - passwords: show/hide passwords
#   - use FILE_log.txt for more info (number of A, B, total flows, ...)

T2FMDIR="$(dirname "$0")"

source "$T2FMDIR/../t2utils.sh"

REQUIRED_PLUGINS=(
    basicFlow
    basicStats
    txtSink
)

OPTIONAL_PLUGINS=(
    arpDecode
    dnsDecode
    #geoip # deprecated by basicFlow
    httpSniffer
    nDPI
    portClassifier
    pwX
    #ssDecode
    sshDecode
)

REQUIRED_COLS=(
    # basicFlow
    dir
    flowStat
    timeFirst
    timeLast
    duration
    srcIP4,srcIP6,srcIP
    dstIP4,dstIP6,dstIP
    srcPort
    dstPort
    l4Proto

    # basicStats
    numPktsSnt
    numPktsRcvd
    numBytesSnt
    numBytesRcvd
)

OPTIONAL_COLS=(
    # arpDecode
    #arpStat

    # basicFlow
    #srcIPCC     # If present, favoured over geoip
    #dstIPCC     # If present, favoured over geoip

    # dnsDecode
    #dnsAname
    #dnsQname
    #dnsStat
    #dns4Aaddress
    #dns6Aaddress

    # geoip
    #srcIpCountry
    #dstIpCountry

    # httpSniffer
    #httpUsrAg
    #httpHosts
    #httpServ
    #httpRSCode

    # nDPI
    #nDPIclass

    # portClassifier
    #dstPortClass
    #dstPortClassN

    # pwX
    #pwxType
    #pwxUser
    #pwxPass

    # ssDecode/sshDecode
    #sshVersion
)

# Settings
HRNUM=0                 # 0: human readable, 1: raw and human readable, 2: raw
CHART_N=5               # Number of values to display in charts
TABLE_N=10              # Number of values to display in tables
COLOR="\\\\altrowcolor" # Charts color (cyan, red, orange, gray!25, ...)
LOGAXIS=1               # Whether to use logarithmic Y axis

AUTHOR="Tranalyzer Development Team"
TITLE="Tranalyzer Report"

usage() {
    printf "Usage:\n"
    printf "    $SNAME [OPTION...] <INPUT>\n"
    printf "\nInput:\n"
    printf "    -i iface            Interface to capture traffic from\n"
    printf "    -r pcap             PCAP file to analyse\n"
    printf "    -R list             List of PCAP files to analyse\n"
    printf "    -F file             Flow file to analyse\n"
    printf "\nOptional arguments:\n"
    printf "    -b                  Configure and build Tranalyzer2 and the plugins\n\n"
    printf "    -A                  Automatically open the generated PDF\n\n"
    printf "    -f factor           Hash table multiplication factor\n"
    printf "    -o folder           Output folder\n"
    printf "    -w prefix           Output prefix\n\n"
    printf "    -t title            Set the report title\n"
    printf "    -a author           Set the report author\n"
    printf "    -c color            Set the charts color (red, orange, gray!25, ...)\n"
    printf "    -L                  Do not use logarithmic scale for axis\n"
    printf "    -H                  Output raw numbers instead of human readable\n"
    printf "    -HH                 Output raw and human readable numbers\n"
    printf "    -n num              Compute top num statistics for tables [default: $TABLE_N]\n"
    printf "    -m num              Compute top num statistics for charts [default: $CHART_N]\n\n"
    printf "    -?, -h, --help      Show help options and exit\n"
}

_build_t2() {
    # Patch tranalyzer and the plugins
    $T2HOME/scripts/t2conf/t2conf -x --patch "$T2FMDIR/t2fm.patch" || exit 1
    # Build tranalyzer and the plugins
    $T2HOME/autogen.sh -b "$T2FMDIR/t2fm.load" || exit 1
}

_check_t2_plugins() {
    for i in ${REQUIRED_PLUGINS[@]}; do
        if [ ! -f "$HOME/.tranalyzer/plugins/"[0-9][0-9][0-9]_${i}.so ]; then
            printerr "Plugin '$i' is required"
            exit 1
        fi
    done
}

_check_colnames() {
    for i in ${REQUIRED_COLS[@]}; do
        i="$($SED 's/,/\\|/g' <<< "$i")"
        if [ -z "$($TAWK -l "$FLOWFILE" | grep -w "$i")" ]; then
            printerr "Column '$i' not found."
            exit 1
        fi
    done
}

_cleanup() {
    if [ -z "$1" ]; then
        printerr "cleanup: missing return code (cleanup retcode)"
        exit 1
    fi

    local ret=$1

    #printinf "Cleaning temporary files"
    for i in ${TEMP[@]}; do
        rm -f $i
    done

    if [ "$(pgrep -P $$ | wc -l)" -gt 1 ]; then
        printinf "Killing all subprocesses..."
        kill -- -$$
    fi

    exit $ret
}

# Load tawk examples
TAWK="$TAWK -e"

while [ $# -gt 0 ]; do
    case "$1" in
        -b|--build)
            BUILD_T2=1
            ;;
        -A|--open-pdf)
            OPENPDF=1
            ;;
        -f|--hash-factor)
            validate_next_num "$1" "$2"
            HASHFACTOR="-f $2"
            shift
            ;;
        -i|--iface)
            validate_next_arg "$1" "$2"
            IFACE="$2"
            shift
            ;;
        -r|--pcap)
            validate_next_pcap "$1" "$2"
            PCAP="$2"
            shift
            ;;
        -R|--caplist)
            validate_next_file "$1" "$2"
            PCAPLIST="$2"
            shift
            ;;
        -F|--flow-file)
            validate_next_file "$1" "$2"
            FLOWFILE="$2"
            shift
            ;;
        -o|--output-folder)
            validate_next_arg "$1" "$2"
            ODIR="$2"
            shift
            ;;
        -w|--output-prefix)
            validate_next_arg "$1" "$2"
            OPREF="$2"
            shift
            ;;
        -c|--color)
            validate_next_arg "$1" "$2"
            COLOR="$2"
            shift
            ;;
        -L|--no-log-axis) LOGAXIS=0;;
        -a|--author)
            validate_next_arg "$1" "$2"
            AUTHOR="$2"
            shift
            ;;
        -t|--title)
            validate_next_arg "$1" "$2"
            TITLE="$2"
            shift
            ;;
        -n|--table-n)
            validate_next_num "$1" "$2"
            TABLE_N="$2"
            shift
            ;;
        -m|--chart-n)
            validate_next_num "$1" "$2"
            CHART_N="$2"
            shift
            ;;
        -H|--raw-numbers)
            HRNUM=2
            ;;
        -HH|--raw-and-hrnum)
            HRNUM=1
            ;;
        -\?|-h|--help) usage; exit 0;;
        *)
            abort_option_unknown "$1"
            ;;
    esac
    shift
done

INFILE="$FLOWFILE$PCAP$PCAPLIST"
INPUT="$IFACE$INFILE"

if [ -z "$INPUT" ]; then
    printerr "One of -F, -i, -r or -R option is required"
    abort_with_help
fi

if [ "$INPUT" != "$IFACE" ] &&
   [ "$INPUT" != "$PCAP" ] &&
   [ "$INPUT" != "$PCAPLIST" ] &&
   [ "$INPUT" != "$FLOWFILE" ]
then
    printerr "Cannot use -F, -i, -r and -R options at the same time"
    abort_with_help
fi

if [ -n "$ODIR" ] && [ ! -d "$ODIR" ]; then
    printf "Output folder '$ODIR' does not exist... create it? "
    read ans
    case $ans in
        N|n) exit 0
    esac
    mkdir -p "$ODIR"
    printf "Folder '$ODIR' created\n"
fi

if [ $LOGAXIS -eq 1 ]; then
    AXIS="semilogyaxis"
    LOG=" [log]"
else
    AXIS="axis"
    LOG=""
fi

if [ -n "$BUILD_T2" ]; then
    _build_t2
fi

if [ -n "$FLOWFILE" ]; then
    HDR="$($SED 's/_flows.txt/_headers.txt/' <<< "$FLOWFILE")"
    if [ ! -f "$HDR" ]; then
        printwrn "Header file not found"
    else
        PCAP="$(grep 'Command line: ' "$HDR" | grep -- -r | perl -pe 's/.*-r\s+([^[:space:]]+)\s+.*$/\1/')"
    fi
else
    _check_t2_plugins

    # Output folder
    if [ -z "$ODIR" ]; then
        ODIR="$(dirname "$INPUT")"
    fi
    if [ -n "$OPREF" ]; then
        PREFIX="$OPREF"
    else
        PREFIX="$(basename "$INPUT" | $AWK -F'.' -v OFS='.' '{ if (NF > 1) NF--; print }')"
    fi
    if [ -z "$PREFIX" ]; then
        PREFIX="$INPUT"
    fi
    PREFIX="$ODIR/$PREFIX"

    FLOWFILE="$($AWK '{ printf "%s_flows.txt\n", $0 }' <<< "$PREFIX")"
    if [ -n "$PCAPLIST" ]; then
        T2OPTS="-R"
    elif [ -n "$IFACE" ]; then
        T2OPTS="-i"
    else
        T2OPTS="-r"
    fi
    printinf "Running Tranalyzer"
    $T2 $T2OPTS "$INPUT" -w "$PREFIX" -l $HASHFACTOR
    if [ $? -ne 0 ]; then
        printwrn "Failed to run Tranalyzer"
        printinf "Trying to generate the report anyway..."
    else
        printinf "Generating report..."
    fi
fi

if [ ! -f "$FLOWFILE" ]; then
    printerr "Flow file '$FLOWFILE' does not exist"
    exit 1
fi

_check_colnames

# Build output filename
[ -z "$OPREF" ] && OPREF="$(basename "$FLOWFILE" | $SED 's/_flows\.[^\.]\+$//')"
[ -z "$ODIR" ] && ODIR="$(dirname "$FLOWFILE")"
OFILE="$($READLINK -f "$ODIR/${OPREF}.tex")"
PDFFILE="$($SED 's/\.tex/.pdf/' <<< "$OFILE")"

# Copy the template
cp "$T2HOME/scripts/t2fm/t2fm_template.tex" "$OFILE"

# Setup signal handler to take care of temporary files
trap "trap - SIGTERM && _cleanup 1" HUP INT QUIT TERM
trap "_cleanup 0" EXIT

#LOG="$($SED 's/_flows.txt/_log.txt/' <<< "$FLOWFILE")"
#if [ ! -f "$LOG" ]; then
#    printerr "Log file not found"
#fi

################################################################################
# Temporary files
################################################################################

# Summary
FIRST_LAST_DUR_NPKTS=$(mktemp); TEMP+=($FIRST_LAST_DUR_NPKTS)
MD5SUM=$(mktemp)              ; TEMP+=($MD5SUM)

# Source and Destination IP
SHOST_CN_FLOWS=$(mktemp) ; TEMP+=($SHOST_CN_FLOWS)
DHOST_CN_FLOWS=$(mktemp) ; TEMP+=($DHOST_CN_FLOWS)
SHOST_CN_PKTS=$(mktemp)  ; TEMP+=($SHOST_CN_PKTS)
DHOST_CN_PKTS=$(mktemp)  ; TEMP+=($DHOST_CN_PKTS)
SHOST_CN_BYTES=$(mktemp) ; TEMP+=($SHOST_CN_BYTES)
DHOST_CN_BYTES=$(mktemp) ; TEMP+=($DHOST_CN_BYTES)

# Source and Destination Countries
SRC_CC_FLOWS=$(mktemp) ; TEMP+=($SRC_CC_FLOWS)
DST_CC_FLOWS=$(mktemp) ; TEMP+=($DST_CC_FLOWS)
SRC_CC_PKTS=$(mktemp)  ; TEMP+=($SRC_CC_PKTS)
DST_CC_PKTS=$(mktemp)  ; TEMP+=($DST_CC_PKTS)
SRC_CC_BYTES=$(mktemp) ; TEMP+=($SRC_CC_BYTES)
DST_CC_BYTES=$(mktemp) ; TEMP+=($DST_CC_BYTES)

# Source and Destination Ports
FLOWS_DPORT=$(mktemp)    ; TEMP+=($FLOWS_DPORT)
FLOWS_SPORT=$(mktemp)    ; TEMP+=($FLOWS_SPORT)
PKTS_DPORT=$(mktemp)     ; TEMP+=($PKTS_DPORT)
PKTS_SPORT=$(mktemp)     ; TEMP+=($PKTS_SPORT)
BYTES_DPORT=$(mktemp)    ; TEMP+=($BYTES_DPORT)
BYTES_SPORT=$(mktemp)    ; TEMP+=($BYTES_SPORT)

# Protocols and Applications
FLOWS_PROTO=$(mktemp)    ; TEMP+=($FLOWS_PROTO)
APP_FLOWS=$(mktemp)      ; TEMP+=($APP_FLOWS)
NON_STDPORTS=$(mktemp)   ; TEMP+=($NON_STDPORTS)
PASSWORDS=$(mktemp)      ; TEMP+=($PASSWORDS)

# DNS
DNSA=$(mktemp)           ; TEMP+=($DNSA)
DNSQ=$(mktemp)           ; TEMP+=($DNSQ)
DNSIP4=$(mktemp)         ; TEMP+=($DNSIP4)
DNSIP6=$(mktemp)         ; TEMP+=($DNSIP6)
SLD=$(mktemp)            ; TEMP+=($SLD)
TLD=$(mktemp)            ; TEMP+=($TLD)

# HTTP
USER_AGENTS=$(mktemp)    ; TEMP+=($USER_AGENTS)
HTTP_HOSTS=$(mktemp)     ; TEMP+=($HTTP_HOSTS)
SERVERS=$(mktemp)        ; TEMP+=($SERVERS)
CONTENT_TYPES=$(mktemp)  ; TEMP+=($CONTENT_TYPES)
CONTENTS=$(mktemp)       ; TEMP+=($CONTENTS)
HTTP_STATUS=$(mktemp)    ; TEMP+=($HTTP_STATUS)
EXEDL=$(mktemp)          ; TEMP+=($EXEDL)

# HTTPS
#SNI=$(mktemp)            ; TEMP+=($SNI)
#CERT_CN=$(mktemp)        ; TEMP+=($CERT_CN)

# Warnings
ARPSPOOF=$(mktemp)       ; TEMP+=($ARPSPOOF)
DNSZT=$(mktemp)          ; TEMP+=($DNSZT)
SSH=$(mktemp)            ; TEMP+=($SSH)

################################################################################
# Check for optional plugins
################################################################################

# dnsDecode
if [ -z "$($TAWK -l "$FLOWFILE" | grep -w dnsStat)" ]; then
    NODNSDECODE=1
    $SED -i "s;\(%__BEGIN_DNSDECODE_REQUIRED__\);N/A: dnsDecode plugin required\n\1;" "$OFILE"
    $SED -i "/%__BEGIN_DNSDECODE_REQUIRED__/,/%__END_DNSDECODE_REQUIRED__/d" "$OFILE"
fi

# httpSniffer
if [ -z "$($TAWK -l "$FLOWFILE" | grep -w httpStat)" ]; then
    NOHTTPSNIFFER=1
    $SED -i "s;\(%__BEGIN_HTTPSNIFFER_REQUIRED__\);N/A: httpSniffer plugin required\n\1;" "$OFILE"
    $SED -i "/%__BEGIN_HTTPSNIFFER_REQUIRED__/,/%__END_HTTPSNIFFER_REQUIRED__/d" "$OFILE"
fi

# ssDecode
#if [ -z "$($TAWK -l "$FLOWFILE" | grep -w httpStat)" ]; then
#    NOSSDECODE=1
#    $SED -i "s;\(%__BEGIN_SSDECODE_REQUIRED__\);N/A: ssDecode plugin required\n\1;" "$OFILE"
#    $SED -i "/%__BEGIN_SSDECODE_REQUIRED__/,/%__END_SSDECODE_REQUIRED__/d" "$OFILE"
#fi

################################################################################
# File stat
################################################################################

if [ -f "$PCAP" ]; then
    FULLNAME="$PCAP" # $($SED 's/_/\\_/g' <<< "$PCAP")"
    FILENAME="$($AWK -F/ '{print $NF}' <<< "$FULLNAME")"
    FILESIZE="$(du -h "$PCAP" | $AWK '{ print $1 }')"
    if [ "$(uname)" = "Darwin" ]; then
        md5 "$PCAP" | $AWK '{ print $4 }' > $MD5SUM &
    else
        md5sum "$PCAP" | $AWK '{ print $1 }' > $MD5SUM &
    fi
else
    #printwrn "PCAP file $PCAP not found"
    FULLNAME="N/A"
    FILENAME="$INPUT" # $($SED 's/_/\\_/g' <<< "$FLOWFILE")"
    FILESIZE="N/A"
    echo "N/A" > $MD5SUM
fi

################################################################################
# Summary
################################################################################

# TODO Extract info from FILE_log.txt (A, B, total flows, ...)

# Time/Duration
$TAWK -H '
    BEGIN { tFirst = -1 }
    tFirst < 0 { tFirst = $timeFirst }
    tFirst > $timeFirst { tFirst = $timeFirst }
    tLast  < $timeLast  { tLast  = $timeLast  }
    { nPkts += $numPktsSnt }
    END {
        _ts = timestamp(tFirst)
        _te = timestamp(tLast)
        print _ts, _te, _te - _ts, hrnum(nPkts, 1)
    }' "$FLOWFILE" > $FIRST_LAST_DUR_NPKTS &

# TODO parallel
HOSTS="$($TAWK '!hdr() { print shost() "\n" dhost() }' "$FLOWFILE" | sort -u)"
DISTINCTIP="$(wc -l <<< "$HOSTS" | $TAWK '{ print hrnum($1, 1) }')"
DISTINCTPRIVIP="$($TAWK 'privip($1)' <<< "$HOSTS" | wc -l | $TAWK '{ print hrnum($1, 1) }')"
DISTINCTPUBIP="$($TAWK '!privip($1)' <<< "$HOSTS" | wc -l | $TAWK '{ print hrnum($1, 1) }')"

################################################################################
# Top Source/Destination IP addresses
################################################################################

# $1: value to aggregate
# $2: file where to write the result
topSrcIP() {
    if [ -z "$2" ]; then
        echo "Usage: topSrcIP aggrval destfile"
        exit 1
    fi
    $TAWK -t -v n="$TABLE_N" -v val="$1" '
        hdr() {
            _sip = _validate_col("srcIP4;srcIP6;srcIP", _my_srcIP)
            _dip = _validate_col("dstIP4;dstIP6;dstIP", _my_dstIP)
            next
        }
        streq($dir, "A") && !bitisset($flowStat, 1) {
            if (srcIPCC != 0) {
                country = toupper($srcIPCC)
                if (country ~ /^[0-9]/) country = "--"
                else if (country == "FF" || country == "--") country = "N/A"
            } else if (srcIpCountry == 0) {
                if (privip($_sip)) country = "--"
                else country = "N/A"
            } else {
                country = $srcIpCountry
            }
            if (streqi(val, "pkts")) _val = $numPktsSnt
            else if (streqi(val, "bytes")) _val = $numBytesSnt
            else _val = "flows"
            aggr($_sip OFS country, _val, n+10)
        }
        streq($dir, "A") && bitisset($flowStat, 1) {
            if (dstIPCC != 0) {
                country = toupper($dstIPCC)
                if (country ~ /^[0-9]/) country = "--"
                else if (country == "FF" || country == "--") country = "N/A"
            } else if (dstIpCountry == 0) {
                if (privip($_dip)) country = "--"
                else country = "N/A"
            } else {
                country = $dstIpCountry
            }
            if (streqi(val, "pkts")) _val = $numPktsRcvd
            else if (streqi(val, "bytes")) _val = $numBytesRcvd
            else _val = "flows"
            aggr($_dip OFS country, _val, n+10)
        }' "$FLOWFILE" | $TAWK -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '{
            if (NR > n) printf "%%"
            print $1 " & " $2 " & " hrnum($3, hrnum_mode) "\\\\"
        } END {
            for (i = NR; i < n; i++) print "\\rowcolor{white}&&\\\\"
        }' > "$2" &
}

# $1: value to aggregate
# $2: file where to write the result
topDstIP() {
    if [ -z "$2" ]; then
        echo "Usage: topDstIP aggrval destfile"
        exit 1
    fi
    $TAWK -t -v n="$TABLE_N" -v val="$1" '
        hdr() {
            _sip = _validate_col("srcIP4;srcIP6;srcIP", _my_srcIP)
            _dip = _validate_col("dstIP4;dstIP6;dstIP", _my_dstIP)
            next
        }
        streq($dir, "A") && !bitisset($flowStat, 1) {
            if (dstIPCC != 0) {
                country = toupper($dstIPCC)
                if (country ~ /^[0-9]/) country = "--"
                else if (country == "FF" || country == "--") country = "N/A"
            } else if (dstIpCountry == 0) {
                if (privip($_dip)) country = "--"
                else country = "N/A"
            } else {
                country = $dstIpCountry
            }
            if (streqi(val, "pkts")) _val = $numPktsRcvd
            else if (streqi(val, "bytes")) _val = $numBytesRcvd
            else _val = "flows"
            aggr($_dip OFS country, _val, n+10)
        }
        streq($dir, "A") && bitisset($flowStat, 1) {
            if (srcIPCC != 0) {
                country = toupper($srcIPCC)
                if (country ~ /^[0-9]/) country = "--"
                else if (country == "FF" || country == "--") country = "N/A"
            } else if (srcIpCountry == 0) {
                if (privip($_sip)) country = "--"
                else country = "N/A"
            } else {
                country = $srcIpCountry
            }
            if (streqi(val, "pkts")) _val = $numPktsSnt
            else if (streqi(val, "bytes")) _val = $numBytesSnt
            else _val = "flows"
            aggr($_sip OFS country, _val, n+10)
        }' "$FLOWFILE" | $TAWK -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '{
            if (NR > n) printf "%%"
            print $1 " & " $2 " & " hrnum($3, hrnum_mode) "\\\\"
        } END {
            for (i = NR; i < n; i++) print "\\rowcolor{white}&&\\\\"
        }' > "$2" &
}

topSrcIP flows $SHOST_CN_FLOWS
topSrcIP pkts  $SHOST_CN_PKTS
topSrcIP bytes $SHOST_CN_BYTES

topDstIP flows $DHOST_CN_FLOWS
topDstIP pkts  $DHOST_CN_PKTS
topDstIP bytes $DHOST_CN_BYTES

################################################################################
# Top Source/Destination countries
################################################################################

# $1: value to aggregate
# $2: file where to write the result
topSrcCC() {
    if [ -z "$2" ]; then
        echo "Usage: topSrcCC aggrval destfile"
        exit 1
    fi
    $TAWK -v n="$TABLE_N" -v val="$1" '
        hdr() { next }
        streq($dir, "A") && !bitisset($flowStat, 1) {
            if (srcIPCC != 0) {
                country = toupper($srcIPCC)
                if (country ~ /^[0-9]/) country = "--"
                else if (country == "FF" || country == "--") country = "N/A"
            } else if (srcIpCountry == 0) {
                if (privip(shost())) country = "--"
                else country = "N/A"
            } else {
                country = $srcIpCountry
            }
            if (streqi(val, "pkts")) _val = $numPktsSnt
            else if (streqi(val, "bytes")) _val = $numBytesSnt
            else _val = "flows"
            aggr(country, _val, n+10)
        }
        streq($dir, "A") && bitisset($flowStat, 1) {
            if (dstIPCC != 0) {
                country = toupper($dstIPCC)
                if (country ~ /^[0-9]/) country = "--"
                else if (country == "FF" || country == "--") country = "N/A"
            } else if (dstIpCountry == 0) {
                if (privip(dhost())) country = "--"
                else country = "N/A"
            } else {
                country = $dstIpCountry
            }
            if (streqi(val, "pkts")) _val = $numPktsRcvd
            else if (streqi(val, "bytes")) _val = $numBytesRcvd
            else _val = "flows"
            aggr(country, _val, n+10)
        }' "$FLOWFILE" | $TAWK -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '{
            if (NR > n) printf "%%"
            print $1 " & " hrnum($2, hrnum_mode) "\\\\"
        } END {
            for (i = NR; i < n; i++) print "\\rowcolor{white}&\\\\"
        }' > "$2" &
}

# $1: value to aggregate
# $2: file where to write the result
topDstCC() {
    if [ -z "$2" ]; then
        echo "Usage: topDstCC aggrval destfile"
        exit 1
    fi
    $TAWK -v n="$TABLE_N" -v val="$1" '
        hdr() { next }
        streq($dir, "A") && !bitisset($flowStat, 1) {
            if (dstIPCC != 0) {
                country = toupper($dstIPCC)
                if (country ~ /^[0-9]/) country = "--"
                else if (country == "FF" || country == "--") country = "N/A"
            } else if (dstIpCountry == 0) {
                if (privip(dhost())) country = "--"
                else country = "N/A"
            } else {
                country = $dstIpCountry
            }
            if (streqi(val, "pkts")) _val = $numPktsRcvd
            else if (streqi(val, "bytes")) _val = $numBytesRcvd
            else _val = "flows"
            aggr(country, _val, n+10)
        }
        streq($dir, "A") && bitisset($flowStat, 1) {
            if (srcIPCC != 0) {
                country = toupper($srcIPCC)
                if (country ~ /^[0-9]/) country = "--"
                else if (country == "FF" || country == "--") country = "N/A"
            } else if (srcIpCountry == 0) {
                if (privip(shost())) country = "--"
                else country = "N/A"
            } else {
                country = $srcIpCountry
            }
            if (streqi(val, "pkts")) _val = $numPktsSnt
            else if (streqi(val, "bytes")) _val = $numBytesSnt
            else _val = "flows"
            aggr(country, _val, n+10)
        }' "$FLOWFILE" | $TAWK -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '{
            if (NR > n) printf "%%"
            print $1 " & " hrnum($2, hrnum_mode) "\\\\"
        } END {
            for (i = NR; i < n; i++) print "\\rowcolor{white}&\\\\"
        }' > "$2" &
}

topSrcCC flows $SRC_CC_FLOWS
topSrcCC pkts  $SRC_CC_PKTS
topSrcCC bytes $SRC_CC_BYTES

topDstCC flows $DST_CC_FLOWS
topDstCC pkts  $DST_CC_PKTS
topDstCC bytes $DST_CC_BYTES

################################################################################
# Top Destination/Source Ports
################################################################################

# $1: value to aggregate
# $2: file where to write the result
topSrcPort() {
    if [ -z "$2" ]; then
        echo "Usage: topSrcPort aggrval destfile"
        exit 1
    fi
    $TAWK -v n="$CHART_N" -v val="$1" '
        hdr() { next }
        !tcp() && !udp() { next }
        streq($dir, "A") && !bitisset($flowStat, 1) {
            if (streqi(val, "pkts")) _val = $numPktsSnt
            else if (streqi(val, "bytes")) _val = $numBytesSnt
            else _val = "flows"
            aggr(sport(), _val, n)
        }
        streq($dir, "A") && bitisset($flowStat, 1) {
            if (streqi(val, "pkts")) _val = $numPktsRcvd
            else if (streqi(val, "bytes")) _val = $numBytesRcvd
            else _val = "flows"
            aggr(dport(), _val, n)
        }' "$FLOWFILE" | $AWK -F'\t' -v n="$CHART_N" -v color="$COLOR" '{
            a[NR,"port"] = $1
            a[NR,"count"] = $2
        } END {
            vmax = NR < n ? NR : n
            for (i = 1; i < vmax; i++) printf "%s,", a[i,"port"]
            printf "%s}]\n", a[i,"port"]
            printf "\\addplot[fill=%s] coordinates {\n", color
            for (i = 1; i <= vmax; i++) printf "(%s,%s)\n", a[i,"port"], a[i,"count"]
        }' > "$2" &
}

# $1: value to aggregate
# $2: file where to write the result
topDstPort() {
    if [ -z "$2" ]; then
        echo "Usage: topDstPort aggrval destfile"
        exit 1
    fi
    $TAWK -v n="$CHART_N" -v val="$1" '
        hdr() { next }
        !tcp() && !udp() { next }
        streq($dir, "A") && !bitisset($flowStat, 1) {
            if (streqi(val, "pkts")) _val = $numPktsRcvd
            else if (streqi(val, "bytes")) _val = $numBytesRcvd
            else _val = "flows"
            aggr(dport(), _val, n)
        }
        streq($dir, "A") && bitisset($flowStat, 1) {
            if (streqi(val, "pkts")) _val = $numPktsSnt
            else if (streqi(val, "bytes")) _val = $numBytesSnt
            else _val = "flows"
            aggr(sport(), _val, n)
        }' "$FLOWFILE" | $AWK -F'\t' -v n="$CHART_N" -v color="$COLOR" '{
            a[NR,"port"] = $1
            a[NR,"count"] = $2
        } END {
            vmax = NR < n ? NR : n
            for (i = 1; i < vmax; i++) printf "%s,", a[i,"port"]
            printf "%s}]\n", a[i,"port"]
            printf "\\addplot[fill=%s] coordinates {\n", color
            for (i = 1; i <= vmax; i++) printf "(%s,%s)\n", a[i,"port"], a[i,"count"]
        }' > "$2" &
}

topSrcPort flows $FLOWS_SPORT
topSrcPort pkts  $PKTS_SPORT
topSrcPort bytes $BYTES_SPORT

topDstPort flows $FLOWS_DPORT
topDstPort pkts  $PKTS_DPORT
topDstPort bytes $BYTES_DPORT

################################################################################
# Protocols
################################################################################

$TAWK -v n="$CHART_N" '!hdr() { aggr(proto(), "flows", n) }' "$FLOWFILE" |
    $TAWK -v n="$CHART_N" -v color="$COLOR" '{
        a[NR,"proto"] = $1
        a[NR,"count"] = $2
    } END {
        vmax = NR < n ? NR : n
        for (i = 1; i < vmax; i++) printf "%s,", chomp(a[i,"proto"])
        printf "%s}]\n", a[i,"proto"]
        printf "\\addplot[fill=%s] coordinates {\n", color
        for (i = 1; i <= vmax; i++) printf "(%s,%s)\n", chomp(a[i,"proto"]), a[i,"count"]
    }' > $FLOWS_PROTO &

################################################################################
# Applications
################################################################################

# TODO add percentage?
NAPPL=15
$TAWK -v n="$NAPPL" '
    BEGIN {
        if (nDPIclass == 0) {
            print "\\multicolumn{2}{c}{N/A: nDPI plugin required}\\\\"
            exit
        }
    }
    !hdr() {
        ndpiClass = gensub(/\..*/, "", 1, unquote($nDPIclass)) # master protocol only
        aggr(ndpiClass, "flows", n+10)
    }' "$FLOWFILE" | $TAWK -v n="$NAPPL" -v color="$COLOR" -v hrnum_mode="$HRNUM" '
        NF == 1 {
            print
            exit
        }
        NF > 1 {
            if (NR > n) printf "%%"
            print texscape($1) " & " hrnum($2, hrnum_mode) "\\\\"
        }' > $APP_FLOWS &

################################################################################
# Protocols Over Non-Standard Ports
################################################################################

$TAWK -v n="$TABLE_N" '
    BEGIN {
        # Only one of dstPortClass/dstPortClassN is required
        if (nDPIclass == 0 || (dstPortClass == 0 && dstPortClassN == 0)) {
            print "N/A: nDPI and portClassifier plugins required\n"
            exit
        }
    }
    hdr() { next }
    nonstdports() && $nDPIclass !~ /Skype/ && $nDPIclass !~ /BitTorrent/ && $nDPIclass !~ /H323/ {
        ndpiClass = gensub(/\..*/, "", 1, unquote($nDPIclass)) # master protocol only
        if (dstPortClassN && dstPortClass) {
            aggr(ndpiClass OFS $dstPortClassN OFS $dstPortClass, $numBytesSnt OFS $numPktsSnt OFS "Flows", n+10)
        } else if (dstPortClass) {
            aggr(ndpiClass OFS $dstPortClass, $numBytesSnt OFS $numPktsSnt OFS "Flows", n+10)
        } else {
            aggr(ndpiClass OFS $dstPortClassN, $numBytesSnt OFS $numPktsSnt OFS "Flows", n+10)
        }
    }' "$FLOWFILE" | $TAWK -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '
        NF == 1 {
            error = $0
            exit
        }
        NR == 1 {
            print "\\begin{longtable}{llrrr}"
            print "\\toprule\\rowcolor{white}"
            print "{\\bf Detected} & {\\bf Expected} & {\\bf Bytes} & {\\bf Packets} & {\\bf Flows}\\\\"
            print "\\midrule\\endhead%"
        }
        {
            if (NR > n) printf "%%"
            if (NF == 5) {
                portnum = $2
                stats = hrnum($3, hrnum_mode) " & " hrnum($4, hrnum_mode) " & " hrnum($5, hrnum_mode)
            } else {
                portnum = texscape($3) " (" $2 ")"
                stats = hrnum($4, hrnum_mode) " & " hrnum($5, hrnum_mode) " & " hrnum($6, hrnum_mode)
            }
            print texscape($1) " & " portnum " & " stats "\\\\"
        }
        END {
            if (error) print error
            else if (NR < 1) print "None detected"
            else print "\\bottomrule\n\\end{longtable}"
        }' > $NON_STDPORTS &

################################################################################
# Cleartext Passwords
################################################################################

if [ -z "$($TAWK -l "$FLOWFILE" | grep -w pwxType)" ]; then
    printf "N/A: pwX plugin required\n" > $PASSWORDS &
else
    $TAWK -v n="$TABLE_N" 'passwords("Flows", n+10)' "$FLOWFILE" | $TAWK -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '
        NR == 1 {
            tabhdr = sprintf("\\begin{longtable}{*{%s}{l}r}\n\\toprule\\rowcolor{white}\n", NF-1)
            $0 = texscape($0)
            for (i = 1; i < NF; i++) tabhdr = tabhdr "\n" sprintf("{\\bf %s} & ", $i)
            tabhdr = tabhdr sprintf("{\\bf %s}\\\\\n\\midrule\\endhead%\n", $NF)
        }
        NR > 1 {
            # ignore empty username and passwords
            if ((strisempty($4) && strisempty($5)) ||
                (streq($4, "(null)") && streq($5, "(null)")))
            {
                next;
            }
            if (tabhdr) {
                print tabhdr
                tabhdr = ""
            }
            if (NR > n+1) printf "%%" # do not count the header
            for (i = 1; i < NF; i++) printf "%s & ", texscape(unquote($i))
            printf "%s\\\\\n", hrnum($NF, hrnum_mode)
        }
        END {
            if (NR == 1) printf "None detected\n"
            else printf "\\bottomrule\n\\end{longtable}\n"
        }' > $PASSWORDS &
fi

################################################################################
# DNS
################################################################################

if [ -z "$NODNSDECODE" ]; then

    #---------------------------------------------------------------------------
    # DNS Queries
    #---------------------------------------------------------------------------

    $TAWK -H -v n="$TABLE_N" 'topDnsQ(n+10)' "$FLOWFILE" | $TAWK -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '
        BEGIN {
            print "\\begin{tabularx}{\\textwidth}{Lr}"
            print "\\toprule"
            print "{\\bf DNS Query} & {\\bf Count}\\\\"
            print "\\midrule"
        }
        {
            if (NR > n) printf "%%"
            print texscape($1) " & " hrnum($2, hrnum_mode) "\\\\"
        }
        END {
            if (NR < 1) {
                for (i = 0; i < n/2-1; i++) print "\\rowcolor{white}&\\\\"
                print "\\rowcolor{white}\\multicolumn{2}{c}{No DNS query detected}\\\\"
                for (i = n/2; i < n; i++) print "\\rowcolor{white}&\\\\"
            } else {
                for (i = NR; i < n; i++) print "\\rowcolor{white}&\\\\"
            }
            print "\\bottomrule"
            print "\\end{tabularx}"
        }' > $DNSQ &

    #---------------------------------------------------------------------------
    # DNS Answers
    #---------------------------------------------------------------------------

    $TAWK -H -v n="$TABLE_N" 'topDnsA(n+10)' "$FLOWFILE" | $TAWK -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '
        BEGIN {
            print "\\begin{tabularx}{\\textwidth}{Lr}"
            print "\\toprule"
            print "{\\bf DNS Answer} & {\\bf Count}\\\\"
            print "\\midrule"
        }
        {
            if (NR > n) printf "%%"
            print texscape($1) " & " hrnum($2, hrnum_mode) "\\\\"
        }
        END {
            if (NR < 1) {
                for (i = 0; i < n/2-1; i++) print "\\rowcolor{white}&\\\\"
                print "\\rowcolor{white}\\multicolumn{2}{c}{No DNS answer detected}\\\\"
                for (i = n/2; i < n; i++) print "\\rowcolor{white}&\\\\"
            } else {
                for (i = NR; i < n; i++) print "\\rowcolor{white}&\\\\"
            }
            print "\\bottomrule"
            print "\\end{tabularx}"
        }' > $DNSA &

    #---------------------------------------------------------------------------
    # DNS IPv4 Addresses
    #---------------------------------------------------------------------------

    $TAWK -H -v n="$TABLE_N" 'topDnsIp4(n+10)' "$FLOWFILE" | $TAWK -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '
        BEGIN {
            print "\\begin{center}"
            print "\\begin{tabularx}{\\textwidth}{Rr}"
            print "\\toprule"
            print "{\\bf DNS IPv4 Address} & {\\bf Count}\\\\"
            print "\\midrule"
        }
        {
            if (NR > n) printf "%%"
            print $1 " & " hrnum($2, hrnum_mode) "\\\\"
        }
        END {
            if (NR < 1) {
                for (i = 0; i < n/2-1; i++) print "\\rowcolor{white}&\\\\"
                print "\\rowcolor{white}\\multicolumn{2}{c}{No DNS IPv4 address detected}\\\\"
                for (i = n/2; i < n; i++) print "\\rowcolor{white}&\\\\"
            } else {
                for (i = NR; i < n; i++) print "\\rowcolor{white}&\\\\"
            }
            print "\\bottomrule"
            print "\\end{tabularx}"
            print "\\end{center}"
        }' > $DNSIP4 &

    #---------------------------------------------------------------------------
    # DNS IPv6 Addresses
    #---------------------------------------------------------------------------

    $TAWK -H -v n="$TABLE_N" 'topDnsIp6(n+10)' "$FLOWFILE" | $TAWK -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '
        BEGIN {
            print "\\begin{center}"
            print "\\begin{tabularx}{\\textwidth}{Rr}"
            print "\\toprule"
            print "{\\bf DNS IPv6 Address} & {\\bf Count}\\\\"
            print "\\midrule"
        }
        {
            if (NR > n) printf "%%"
            print $1 " & " hrnum($2, hrnum_mode) "\\\\"
        }
        END {
            if (NR < 1) {
                for (i = 0; i < n/2-1; i++) print "\\rowcolor{white}&\\\\"
                print "\\rowcolor{white}\\multicolumn{2}{c}{No DNS IPv6 address detected}\\\\"
                for (i = n/2; i < n; i++) print "\\rowcolor{white}&\\\\"
            } else {
                for (i = NR; i < n; i++) print "\\rowcolor{white}&\\\\"
            }
            print "\\bottomrule"
            print "\\end{tabularx}"
            print "\\end{center}"
        }' > $DNSIP6 &

    #---------------------------------------------------------------------------
    # Top-Level Domains
    #---------------------------------------------------------------------------

    $TAWK -H -v n="$TABLE_N" 'topTLD(n+10)' "$FLOWFILE" | $TAWK -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '
        BEGIN {
            print "\\begin{tabularx}{\\textwidth}{Rr}"
            print "\\toprule"
            print "{\\bf TLD} & {\\bf Count}\\\\"
            print "\\midrule"
        }
        {
            if (NR > n) printf "%%"
            print $1 " & " hrnum($2, hrnum_mode) "\\\\"
        }
        END {
            if (NR < 1) {
                for (i = 0; i < n/2-1; i++) print "\\rowcolor{white}&\\\\"
                print "\\rowcolor{white}\\multicolumn{2}{c}{No DNS query detected}\\\\"
                for (i = n/2; i < n; i++) print "\\rowcolor{white}&\\\\"
            } else {
                for (i = NR; i < n; i++) print "\\rowcolor{white}&\\\\"
            }
            print "\\bottomrule"
            print "\\end{tabularx}"
        }' > $TLD &

    #---------------------------------------------------------------------------
    # Second-Level Domains
    #---------------------------------------------------------------------------

    $TAWK -H -v n="$TABLE_N" 'topSLD(n+10)' "$FLOWFILE" | $TAWK -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '
        BEGIN {
            print "\\begin{tabularx}{\\textwidth}{Rr}"
            print "\\toprule"
            print "{\\bf SLD} & {\\bf Count}\\\\"
            print "\\midrule"
        }
        {
            if (NR > n) printf "%%"
            print texscape($1) " & " hrnum($2, hrnum_mode) "\\\\"
        }
        END {
            if (NR < 1) {
                for (i = 0; i < n/2-1; i++) print "\\rowcolor{white}&\\\\"
                print "\\rowcolor{white}\\multicolumn{2}{c}{No DNS query detected}\\\\"
                for (i = n/2; i < n; i++) print "\\rowcolor{white}&\\\\"
            } else {
                for (i = NR; i < n; i++) print "\\rowcolor{white}&\\\\"
            }
            print "\\bottomrule"
            print "\\end{tabularx}"
        }' > $SLD &
fi

################################################################################
# HTTP
################################################################################

if [ -z "$NOHTTPSNIFFER" ]; then

    #---------------------------------------------------------------------------
    # HTTP User-Agents
    #---------------------------------------------------------------------------

    $TAWK -H -v n="$TABLE_N" '$httpUsrAg {
        aggrrep($httpUsrAg, "flows", n+10)
    }' "$FLOWFILE" | $TAWK -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '
        BEGIN {
            print "\\begin{center}"
            print "\\begin{tabularx}{\\textwidth}{Lr}"
            print "\\toprule"
            print "{\\bf User-Agent} & {\\bf Count}\\\\"
            print "\\midrule"
        }
        {
            if (NR > n) printf "%%"
            print texscape($1) " & " hrnum($2, hrnum_mode) "\\\\"
        }
        END {
            if (NR < 1) {
                print "\\rowcolor{white}\\multicolumn{2}{c}{No HTTP User-Agent detected}\\\\"
            }
            print "\\bottomrule"
            print "\\end{tabularx}"
            print "\\end{center}"
        }' > $USER_AGENTS &

    #---------------------------------------------------------------------------
    # HTTP Hosts
    #---------------------------------------------------------------------------

    $TAWK -H -v n="$TABLE_N" '$httpHosts {
        aggrrep($httpHosts, "flows", n+10)
    }' "$FLOWFILE" | $TAWK -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '
        BEGIN {
            print "\\begin{tabularx}{\\textwidth}{Lr}"
            print "\\toprule"
            print "{\\bf HTTP Host} & {\\bf Count}\\\\"
            print "\\midrule"
        }
        {
            if (NR > n) printf "%%"
            print texscape($1) " & " hrnum($2, hrnum_mode) "\\\\"
        }
        END {
            if (NR < 1) {
                for (i = 0; i < n/2-1; i++) print "\\rowcolor{white}&\\\\"
                print "\\rowcolor{white}\\multicolumn{2}{c}{No HTTP Host detected}\\\\"
                for (i = n/2; i < n; i++) print "\\rowcolor{white}&\\\\"
            } else {
                for (i = NR; i < n; i++) print "\\rowcolor{white}&\\\\"
            }
            print "\\bottomrule"
            print "\\end{tabularx}"
        }' > $HTTP_HOSTS &

    #---------------------------------------------------------------------------
    # HTTP Servers
    #---------------------------------------------------------------------------

    $TAWK -H -v n="$TABLE_N" '$httpServ {
        aggrrep($httpServ, "flows", n+10)
    }' "$FLOWFILE" | $TAWK -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '
        BEGIN {
            print "\\begin{tabularx}{\\textwidth}{Lr}"
            print "\\toprule"
            print "{\\bf HTTP Server} & {\\bf Count}\\\\"
            print "\\midrule"
        }
        {
            if (NR > n) printf "%%"
            print texscape($1) " & " hrnum($2, hrnum_mode) "\\\\"
        }
        END {
            if (NR < 1) {
                for (i = 0; i < n/2-1; i++) print "\\rowcolor{white}&\\\\"
                print "\\rowcolor{white}\\multicolumn{2}{c}{No HTTP Server detected}\\\\"
                for (i = n/2; i < n; i++) print "\\rowcolor{white}&\\\\"
            } else {
                for (i = NR; i < n; i++) print "\\rowcolor{white}&\\\\"
            }
            print "\\bottomrule"
            print "\\end{tabularx}"
        }' > $SERVERS &

    #---------------------------------------------------------------------------
    # HTTP Content-Types
    #---------------------------------------------------------------------------

    $TAWK -H -v n="$TABLE_N" 'topHttpMimesST(n)' "$FLOWFILE" | $TAWK -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '
        NR == 1 {
            print "\\begin{center}"
            print "\\begin{tabularx}{\\textwidth}{Lr}"
            print "\\toprule"
            print "{\\bf HTTP Content-Type} & {\\bf Count}\\\\"
            print "\\midrule"
        }
        {
            if (NR > n) printf "%%"
            print texscape($1) " & " hrnum($2, hrnum_mode) "\\\\"
        }
        END {
            if (NR < 1) print "No HTTP Content-Type detected"
            else {
                for (i = NR; i < n; i++) print "\\rowcolor{white}&\\\\"
                print "\\bottomrule"
                print "\\end{tabularx}"
                print "\\end{center}"
            }
        }' > $CONTENT_TYPES &

    #---------------------------------------------------------------------------
    # HTTP Contents
    #---------------------------------------------------------------------------

    $TAWK -H -v n="$TABLE_N" 'topHttpMimesT(n+10)' "$FLOWFILE" | $TAWK -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '
        NR == 1 {
            print "\\begin{center}"
            print "\\begin{tabularx}{\\textwidth}{Lr}"
            print "\\toprule"
            print "{\\bf HTTP Content} & {\\bf Count}\\\\"
            print "\\midrule"
        }
        {
            if (NR > n) printf "%%"
            print texscape($1) " & " hrnum($2, hrnum_mode) "\\\\"
        }
        END {
            if (NR < 1) print "\n" # No HTTP Content-Types detected
            else {
                for (i = NR; i < n; i++) print "\\rowcolor{white}&\\\\"
                print "\\bottomrule"
                print "\\end{tabularx}"
                print "\\end{center}"
            }
        }' > $CONTENTS &

    #---------------------------------------------------------------------------
    # HTTP Status Code
    #---------------------------------------------------------------------------

    $TAWK -H '$httpRSCode {
        aggrrep($httpRSCode)
    }' "$FLOWFILE" | $TAWK -v n="$CHART_N" -v color="$COLOR" '{
        a[NR,"statc"] = $1
        a[NR,"count"] = $2
    } END {
        vmax = NR < n ? NR : n
        for (i = 1; i < vmax; i++) printf "%s,", chomp(a[i,"statc"])
        printf "%s}]\n", a[i,"statc"]
        printf "\\addplot[fill=%s] coordinates {\n", color
        for (i = 1; i <= vmax; i++) printf "(%s,%s)\n", chomp(a[i,"statc"]), a[i,"count"]
    }' > $HTTP_STATUS &

    #---------------------------------------------------------------------------
    # EXE Downloads
    #---------------------------------------------------------------------------

    $TAWK -H -v n="$TABLE_N" 'exeDL(n+10)' "$FLOWFILE" | $TAWK -v n="$TABLE_N" '
        NR == 1 {
            print "\\begin{scriptsize}"
            print "\\begin{center}"
            #print "\\begin{tabularx}{\\textwidth}{lllLll}"
            #print "{\\bf SrcIP4} & {\\bf DstIP4} & {\\bf Filename} & {\\bf Size} & {\\bf MD5}\\\\"
            print "\\begin{tabularx}{\\textwidth}{lllLll}"
            #print "\\begin{longtable}{llllll}"
            print "\\toprule"
            print "{\\bf SrcIP4} & {\\bf DstIP4} & {\\bf Advertised Mime} & {\\bf Filename} & {\\bf Size} & {\\bf MD5}\\\\"
            print "\\midrule%\\endhead%"
        }
        {
            # Do not display packet/flow information
            fname = gensub(/^([^?]+)(\?.*)?_[0-9]+_[0-9]+_[0-9]+_[0-9]+$/, "\\1", "g", unquote($4))
            if (NR > n) printf "%%"
            #print $1 " & " $2 " & " texscape(fname) " & " $5 " & " $6"\\\\ % " unquote($4)
            print $1 " & " $2 " & " texscape(unquote($3)) " & \\textnhtt{" texscape(fname) "} & " $5 " & {\\tt " $6 "}\\\\ % " unquote($4)
        }
        END {
            if (NR < 1) print "No EXE download detected"
            else {
                print "\\bottomrule"
                #print "\\end{longtable}"
                print "\\end{tabularx}"
                print "\\end{center}"
                print "\\end{scriptsize}"
            }
        }' > $EXEDL &
fi

################################################################################
# HTTPS
################################################################################

#if [ -z "$NOSSDECODE" ]; then
#
#    #---------------------------------------------------------------------------
#    # HTTPS SNI
#    #---------------------------------------------------------------------------
#
#    $TAWK -H -v n="$TABLE_N" '$sslServerName {
#        aggrrep($sslServerName, "flows", n+10)
#    }' "$FLOWFILE" | $TAWK -v n="$TABLE_N" '
#        NR == 1 {
#            print "\\begin{center}"
#            print "\\begin{tabularx}{\\textwidth}{Lr}"
#            print "\\toprule"
#            print "{\\bf HTTPS SNI} & {\\bf Count}\\\\"
#            print "\\midrule"
#        }
#        {
#            if (NR > n) printf "%%"
#            print texscape($1) " & " $2 "\\\\"
#        }
#        END {
#            if (NR < 1) print "No HTTPS SNI detected"
#            else {
#                for (i = NR; i < n; i++) print "\\rowcolor{white}&\\\\"
#                print "\\bottomrule"
#                print "\\end{tabularx}"
#                print "\\end{center}"
#            }
#        }' > $SNI &
#
#    #---------------------------------------------------------------------------
#    # HTTPS Certificate Common Name
#    #---------------------------------------------------------------------------
#
#    $TAWK -H -v n="$TABLE_N" '$sslCSubjectCommonName {
#        aggrrep($sslCSubjectCommonName, "flows", n+10)
#    }' "$FLOWFILE" | $TAWK -v n="$TABLE_N" '
#        NR == 1 {
#            print "\\begin{center}"
#            print "\\begin{tabularx}{\\textwidth}{Lr}"
#            print "\\toprule"
#            print "{\\bf HTTPS Cert.\\ CN} & {\\bf Count}\\\\"
#            print "\\midrule"
#        }
#        {
#            if (NR > n) printf "%%"
#            print texscape($1) " & " $2 "\\\\"
#        }
#        END {
#            if (NR < 1) print "No HTTPS Certificate Common Name detected"
#            else {
#                for (i = NR; i < n; i++) print "\\rowcolor{white}&\\\\"
#                print "\\bottomrule"
#                print "\\end{tabularx}"
#                print "\\end{center}"
#            }
#        }' > $CERT_CN &
#fi

################################################################################
# Warnings
################################################################################

#-------------------------------------------------------------------------------
# ARP Spoofing
#-------------------------------------------------------------------------------

if [ -z "$($TAWK -l "$FLOWFILE" | grep -w arpStat)" ]; then
    printf "N/A: arpDecode plugin required\n" > $ARPSPOOF &
else
    $TAWK -H 'bitisset($arpStat, 0x80) { print shost() }' "$FLOWFILE" |
    $TAWK -v n="$TABLE_N" '
        NR == 1 {
            print "ARP spoofing detected for:"
            print "\\begin{itemize}"
        }
        NR <= n+10 {
            if (NR > n) printf "%%"
            print "\\item " $1
            next
        }
        NR > n+10 {
            exit
        }
        END{
            if (NR >= 1) print "\\end{itemize}"
            else print "No ARP spoofing detected"
        }' > $ARPSPOOF &
fi

#-------------------------------------------------------------------------------
# DNS Zone Transfers
#-------------------------------------------------------------------------------

$TAWK -H 'dnsZT()' "$FLOWFILE" | $TAWK -v n="$TABLE_N" '
    NR == 1 {
        print "DNS Zone Transfer detected:"
        print "\\begin{longtable}{llll}"
        print "\\toprule\\rowcolor{white}"
        print "{\\bf Time} & {\\bf Client} & {\\bf Server} & {\\bf Query}\\\\"
        print "\\midrule\\endhead%"
    }
    {
        if (NR > n) printf "%%"
        print $1 " & " $2 " & " $3 " & " texscape($4) "\\\\"
    }
    NR > n+10 {
        exit
    }
    END {
        if (NR >= 1) print "\\bottomrule\n\\end{longtable}"
        else print "No DNS zone transfer detected"
    }' > $DNSZT &

#-------------------------------------------------------------------------------
# SSH connections
#-------------------------------------------------------------------------------
# TODO sort table according to SBytes? tawk 't2sort(6, 0, "num")'
HAS_SSH="$($TAWK -l "$FLOWFILE" | grep -w sshVersion | wc -l)"
$TAWK 'not(privip(shost())) || !privip(dhost()) { ssh() }' "$FLOWFILE" |
    $TAWK -v has_ssh="$HAS_SSH" -v n="$TABLE_N" -v hrnum_mode="$HRNUM" '
        NR == 1 {
            str = "\\begin{small}\n"
            str = str "\\begin{tabularx}{\\textwidth}{*{6}{l}L}\n\\toprule"
            #str = str "\\begin{longtable}{*{7}{l}}\n"
            for (i = 1; i < NF; i++) {
                str = str "{\\bf " $i "} & "
            }
            str = str "{\\bf " $NF "}\\\\\n\\midrule\n%\\endhead%\n"
            next
        }
        NR == 2 {
            print str
        }
        NR > 1 {
            if (NR > n+1) printf "%%"
            gsub(/\.[0-9]{6}/, "", $1) # ignore microseconds
            for (i = 1; i < NF-2; i++) {
                printf "%s & ", $i
            }
            printf "%s & %s & ", hrnum($5, hrnum_mode), hrnum($6, hrnum_mode) # sPkts and SBytes
            printf "%s\\\\\n", texscape(unquote($NF)) # ssh version
        }
        NR > n+11 {
            exit
        }
        END {
            if (NR < 2) {
                if (!has_ssh) print "N/A: sshDecode plugin required"
                else print "No SSH connection detected"
            } else {
                print "\\bottomrule"
                print "\\end{tabularx}"
                #print "\\end{longtable}"
                print "\\end{small}"
            }
        }' > $SSH &

################################################################################
# Wait for all the queries to finish
################################################################################

wait < <(jobs -p)

################################################################################
# Format some of the output
################################################################################

FIRST="$($AWK -F'\t' '{ print $1 }' $FIRST_LAST_DUR_NPKTS)"
LAST="$($AWK -F'\t' '{ print $2 }' $FIRST_LAST_DUR_NPKTS)"
DURATION="$($AWK -F'\t' '{ print $3 }' $FIRST_LAST_DUR_NPKTS)"
NUMPKTS="$($AWK -F'\t' '{ print $4 }' $FIRST_LAST_DUR_NPKTS)"
if [ "$(uname)" = "Darwin" ]; then
    UTCFIRST="$(date -u -j -r $FIRST)"
    UTCLAST="$(date -u -j -r $LAST)"
else
    UTCFIRST="$(date -u -d @$FIRST)"
    UTCLAST="$(date -u -d @$LAST)"
fi
DURSTR="$($AWK -v s=$DURATION '
    BEGIN {
        days  = int(s / 3600. / 24.)
        hours = int(s / 3600. - days * 24)
        mins  = int(s / 60. - hours * 60 - days * 24 * 60)
        secs  = s % 60
        if (days + hours + mins) {
            printf "("
            if (days)  printf "%s days", days
            if (hours) printf "%s%s hours", days ? " " : "", hours
            if (mins)  printf "%s%s minutes", days || hours ? " " : "", mins
            if (secs)  printf "%s%s seconds", days || hours || mins ? " " : "", secs
            printf ")\n"
        }
    }')"

################################################################################
# Fill in the placeholders
################################################################################

[ $LOGAXIS -eq 0 ] && $SED -i "s/logaxistrue/logaxisfalse/" "$OFILE"

$SED -i "s/__AUTHOR__/$AUTHOR/" "$OFILE"
$SED -i "s/__TITLE__/$TITLE/" "$OFILE"
$SED -i "s/__COLOR__/$COLOR/" "$OFILE"
$SED -i "s/__TABLE_N__/$TABLE_N/g" "$OFILE"
$SED -i "s/__CHART_N__/$CHART_N/g" "$OFILE"

$SED -i "s;__FILENAME__;$($TAWK '{ print texscape($0) }' <<< "$FILENAME" | $SED 's/\\/\\\\/g');" "$OFILE"
$SED -i "s;__FULLNAME__;$($TAWK '{ print texscape($0) }' <<< "$FULLNAME" | $SED 's/\\/\\\\/g');" "$OFILE"
$SED -i "s;__FILESIZE__;$FILESIZE;" "$OFILE"
$SED -i "s;__MD5SUM__;$(cat $MD5SUM);" "$OFILE"

$SED -i "s/__FIRSTPKT__/$UTCFIRST/" "$OFILE"
$SED -i "s/__LASTPKT__/$UTCLAST/" "$OFILE"
$SED -i "s/__SECONDS__/$DURATION/" "$OFILE"
$SED -i "s/__DURSTR__/$DURSTR/" "$OFILE"
$SED -i "s/__NUMPKTS__/$NUMPKTS/" "$OFILE"

$SED -i "s/__DISTIP__/$DISTINCTIP/" "$OFILE"
$SED -i "s/__PRIVIP__/$DISTINCTPRIVIP/" "$OFILE"
$SED -i "s/__PUBIP__/$DISTINCTPUBIP/" "$OFILE"

#-------------------------------------------------------------------------------
# Top Source/Destination IP addresses
#-------------------------------------------------------------------------------

$SED -i "/__SRCIP_CN_FLOWS__/r$SHOST_CN_FLOWS" "$OFILE"
$SED -i "/__DSTIP_CN_FLOWS__/r$DHOST_CN_FLOWS" "$OFILE"
$SED -i "/__SRCIP_CN_PKTS__/r$SHOST_CN_PKTS" "$OFILE"
$SED -i "/__DSTIP_CN_PKTS__/r$DHOST_CN_PKTS" "$OFILE"
$SED -i "/__SRCIP_CN_BYTES__/r$SHOST_CN_BYTES" "$OFILE"
$SED -i "/__DSTIP_CN_BYTES__/r$DHOST_CN_BYTES" "$OFILE"

#-------------------------------------------------------------------------------
# Top Source/Destination IP countries
#-------------------------------------------------------------------------------

$SED -i "/__SRC_CC_FLOWS__/r$SRC_CC_FLOWS" "$OFILE"
$SED -i "/__DST_CC_FLOWS__/r$DST_CC_FLOWS" "$OFILE"
$SED -i "/__SRC_CC_PKTS__/r$SRC_CC_PKTS" "$OFILE"
$SED -i "/__DST_CC_PKTS__/r$DST_CC_PKTS" "$OFILE"
$SED -i "/__SRC_CC_BYTES__/r$SRC_CC_BYTES" "$OFILE"
$SED -i "/__DST_CC_BYTES__/r$DST_CC_BYTES" "$OFILE"

#-------------------------------------------------------------------------------
# Top Destination/Source Ports
#-------------------------------------------------------------------------------

$SED -i "/__FLOWS_DPORT__/r$FLOWS_DPORT" "$OFILE"
$SED -i "/__FLOWS_SPORT__/r$FLOWS_SPORT" "$OFILE"
$SED -i "/__PKTS_DPORT__/r$PKTS_DPORT" "$OFILE"
$SED -i "/__PKTS_SPORT__/r$PKTS_SPORT" "$OFILE"
$SED -i "/__BYTES_DPORT__/r$BYTES_DPORT" "$OFILE"
$SED -i "/__BYTES_SPORT__/r$BYTES_SPORT" "$OFILE"

#-------------------------------------------------------------------------------
# Protocols and Applications
#-------------------------------------------------------------------------------

$SED -i "/__FLOWS_PROTO__/r$FLOWS_PROTO" "$OFILE"
$SED -i "/__APP_FLOWS__/r$APP_FLOWS" "$OFILE"
$SED -i "/__NON_STD_PORTS__/r$NON_STDPORTS" "$OFILE"
$SED -i "/__PASSWORDS__/r$PASSWORDS" "$OFILE"

#-------------------------------------------------------------------------------
# DNS
#-------------------------------------------------------------------------------

if [ -z "$NODNSDECODE" ]; then
    $SED -i "/__DNSA__/r$DNSA" "$OFILE"
    $SED -i "/__DNSQ__/r$DNSQ" "$OFILE"
    $SED -i "/__DNSIP4__/r$DNSIP4" "$OFILE"
    $SED -i "/__DNSIP6__/r$DNSIP6" "$OFILE"
    $SED -i "/__SLD_FLOWS__/r$SLD" "$OFILE"
    $SED -i "/__TLD_FLOWS__/r$TLD" "$OFILE"
    $SED -i "/__DNS_ZT__/r$DNSZT" "$OFILE"
fi

#-------------------------------------------------------------------------------
# HTTP
#-------------------------------------------------------------------------------

if [ -z "$NOHTTPSNIFFER" ]; then
    $SED -i "/__HTTP_USRAG__/r$USER_AGENTS" "$OFILE"
    $SED -i "/__HTTP_HOSTS__/r$HTTP_HOSTS" "$OFILE"
    $SED -i "/__HTTP_SERVERS__/r$SERVERS" "$OFILE"
    $SED -i "/__HTTP_CONTENTTYPE__/r$CONTENT_TYPES" "$OFILE"
    $SED -i "/__HTTP_CONTENT__/r$CONTENTS" "$OFILE"
    $SED -i "/__HTTP_STATUS__/r$HTTP_STATUS" "$OFILE"
    $SED -i "/__HTTP_EXE_DL__/r$EXEDL" "$OFILE"
fi

#-------------------------------------------------------------------------------
# HTTPS
#-------------------------------------------------------------------------------

#if [ -z "$NOSSDECODE" ]; then
#    $SED -i "/__HTTPS_SNI__/r$SNI" "$OFILE"
#    $SED -i "/__HTTPS_CERT_CN__/r$CERT_CN" "$OFILE"
#fi

#-------------------------------------------------------------------------------
# Warnings
#-------------------------------------------------------------------------------

$SED -i "/__ARP_SPOOF__/r$ARPSPOOF" "$OFILE"
$SED -i "/__SSH_CONN__/r$SSH" "$OFILE"

################################################################################
# Build and display the report
################################################################################

printinf "LaTeX report generated"
printinf "Building the PDF..."

PDFLATEX="pdflatex -output-directory=$ODIR"

$PDFLATEX -halt-on-error -interaction=nonstopmode "$OFILE" > /dev/null && \
    $PDFLATEX "$OFILE" &> /dev/null && \
    $PDFLATEX "$OFILE" > /dev/null

if [ $? -ne 0 ]; then
    printerr "Failed to generate '$PDFFILE'"
    exit 1
fi

printok "Successfully generated '$PDFFILE'" #in X seconds.

# Open the generated file
[ -n "$OPENPDF" ] && $OPEN "$PDFFILE"

exit 0
