#!/usr/bin/env bash
#
# Generates a PDF/LaTeX report from a PCAP, Tranalyzer flow file or database
# (ClickHouse, MongoDB or PostgreSQL).
#
# Usage: t2fm [OPTION...] <INPUT>
#
# 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
#   sshDecode
#   sslDecode
#
# TODO
#   - db backend: add options to choose hostname, port, username, password and table name
#     (or option to pass db.cfg file?)
#
#   - Add elapsed time
#   - Report progress
#   - Add link to virustotal for exe
#   - SCTP ports?
#   - HTTPS:
#       - Add top cert. issuer
#       - Add top unknown JA3 signatures
#       - Add top blacklisted cert
#   - Split top protocols over non-standard ports by bytes, packets and flows
#   - More info in summary (number of A, B, total flows, ...)
#
#   - delete placeholders at the end

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

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

T2FMDIR="$($READLINK -f "$T2FMDIR")"

REQUIRED_PLUGINS=(
    basicFlow
    basicStats
    txtSink
)

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

REQUIRED_COLS=(
    # basicFlow
    dir
    flowStat
    timeFirst
    timeLast
    duration
    srcIP,srcIP4,srcIP6
    dstIP,dstIP4,dstIP6
    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
    #srcIPOrg
    #dstIPOrg

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

    # geoip
    #srcIpCountry # deprecated by srcIPCC (basicFlow)
    #dstIpCountry # deprecated by dstIPCC (basicFlow)

    # httpSniffer
    #httpUsrAg
    #httpHosts
    #httpServ
    #httpRSCode

    # nDPI
    #nDPIclass

    # portClassifier
    #dstPortClass
    #dstPortClassN

    # pwX
    #pwxType
    #pwxUser
    #pwxPass

    # sshDecode
    #sshHassh
    #sshStat
    #sshVersion

    # sslDecode
    #sslServerName
    #sslCSubjectCommonName
    #sslJA3Hash
    #sslJA3Desc
)

# 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
LOGAXIS=1   # Whether to use logarithmic Y axis
POLLINT=1   # Poll interval

# Colors (cyan, red, orange, gray!25, ...)
TABLE_ODD_COLOR="gray!15"           # Background color for odd rows
TABLE_EVEN_COLOR="white"            # Background color for even rows
CHART_COLOR="\\\\altrowcolorodd"    # Charts color

AUTHOR="Tranalyzer Development Team"
TITLE="Tranalyzer Report"
COPYRIGHT="2008-2022 by Tranalyzer Development Team"
WATERMARK="Tranalyzer"

# Sections (uncomment to disable the section)
#NOCOUNTRIES=1
#NOORGANISATIONS=1
#NODNS=1
#NOHTTP=1
#NOHTTPS=1
#NOSSH=1
#NONONSTDPORTS=1
#NOPASSWORDS=1
#NOWARNINGS=1

# Privacy (uncomment to obfuscate)
#HIDEUSER=1
#HIDEPASS=1

usage() {
    printf "Usage:\n"
    printf "    $SNAME [OPTION...] <INPUT>\n"
    printf "\n"
    printf "Input:\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 "    -c dbname          ClickHouse database name\n"
    printf "    -m dbname          Mongo database name\n"
    printf "    -p dbname          PostgreSQL database name\n"
    #printf "    -u username        Database username\n"
    #printf "    -p password        Database password\n"
    #printf "    -H address         Database address\n"
    #printf "    -P port            Database port\n"
    #printf "    -T name            Database table name\n"
    printf "\n"
    printf "Output:\n"
    printf "    -A                 Automatically open the generated PDF\n"
    printf "    -w prefix          Append 'prefix' to any output file produced\n"
    printf "\n"
    printf "Optional arguments:\n"
    printf "    -T from to         Only consider data between from and to [-m and -p only]\n"
    printf "\n"
    printf "    -b                 Configure and build Tranalyzer2 and the plugins\n"
    printf "    --reset            Reset T2 and the plugins configuration at the end\n"
    printf "\n"
    printf "    -f factor          Hash table multiplication factor\n"
    printf "\n"
    printf "    --hide-user        Obfuscate usernames for cleartext passwords\n"
    printf "    --hide-pass        Obfuscate passwords for cleartext passwords\n"
    printf "    --hide-user-pass   Obfuscate usernames and passwords for cleartext passwords\n"
    printf "\n"
    printf "    --no-countries     Do not output top countries\n"
    printf "    --no-organisations Do not output top organisations\n"
    printf "    --no-non-std-ports Do not output non-standard ports statistics\n"
    printf "    --no-dns           Do not output DNS statistics\n"
    printf "    --no-http          Do not output HTTP statistics\n"
    printf "    --no-https         Do not output HTTPS statistics\n"
    printf "    --no-ssh           Do not output SSH statistics\n"
    printf "    --no-passwords     Do not output cleartext passwords\n"
    printf "    --no-warnings      Do not output the warnings section\n"
    printf "\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 "\n"
    printf "    -L                 Do not use logarithmic scale for axis\n"
    printf "\n"
    printf "    -H                 Output raw numbers instead of human readable\n"
    printf "    -HH                Output raw and human readable numbers\n"
    printf "\n"
    printf "    -n num             Compute top num statistics for tables [default: $TABLE_N]\n"
    printf "    -c num             Compute top num statistics for charts [default: $CHART_N]\n"
    printf "\n"
    printf "    --copyright [text] Print a copyright notice at the bottom of every page\n"
    printf "    --watermark [text] Print a watermark on every page\n"
    printf "\n"
    printf "    -y                 Do not ask for confirmation before executing an action\n"
    printf "\n"
    printf "    -0                 Run all queries in parallel\n"
    printf "    -1                 Do not run queries in parallel (slow)\n"
    printf "    -NUM               Run NUM queries in parallel [default: number of cores]\n"
    printf "\n"
    printf "Help and documentation arguments:\n"
    printf "    -?, -h, --help     Show help options and exit\n"
}

_set_db_opref() {
    if [ -n "$MONGODB" ]; then
        OPREF="${DBNAME}_mongo"
    elif [ -n "$CLICKHOUSEDB" ]; then
        OPREF="${DBNAME}_clickhouse"
    else
        OPREF="${DBNAME}_psql"
    fi
}

_set_opref_from_input() {
    if [ -n "$DBNAME" ]; then
        _set_db_opref
    else
        OPREF="$(basename "$INPUT" | AWK -F'.' -v OFS='.' 'NF > 1 { NF-- } { print }')"
    fi
}

# Set output folder/prefix
_set_odir_opref() {
    if [ -z "$OPREF" ]; then
        if [ -n "$DBNAME" ]; then
            ODIR="$PWD"
        else
            ODIR="$(dirname "$INPUT")"
        fi
        _set_opref_from_input
    elif [ -d "$OPREF" ]; then
        ODIR="$OPREF"
        _set_opref_from_input
    elif grep '/' <<< "$OPREF" &> /dev/null; then
        ODIR="$(AWK -F'/' 'NF > 1 { printf "%s", $1; for (i = 2; i < NF; i++) printf "/%s", $i }' <<< "$OPREF")"
        if [ "$(AWK '!/\/$/' <<< "$OPREF")" ]; then
            OPREF="$(basename "$OPREF" | AWK -F'.' -v OFS='.' 'NF > 1 { NF-- } { print }')"
        else
            _set_opref_from_input
        fi
    else
        ODIR="$(dirname "$OPREF")"
        OPREF="$(basename "$OPREF")"
    fi
}

_build_t2() {
    local yes
    if [ "$YES" = "yes" ]; then
        yes="-y"
    fi
    # Patch tranalyzer and the plugins
    $T2CONF $yes -x --patch "$T2FMDIR/t2fm.patch" || exit 1
    # Build tranalyzer and the plugins
    $T2BUILD $yes -b "$T2FMDIR/t2fm.load" || exit 1
}

_reset_t2_config() {
    local yes
    if [ "$YES" = "yes" ]; then
        yes="-y"
    fi
    # Reverse-patch tranalyzer and the plugins
    $T2CONF $yes -x --rpatch "$T2FMDIR/t2fm.patch" || 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() {
    local cols="$1"
    for i in ${REQUIRED_COLS[@]}; do
        i="$($SED 's/,/\\|/g' <<< "$i")"
        if [ -z "$(grep -w "$i" <<< $cols)" ]; 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

    if [ $RESET ]; then
        printinf "Restoring tranalyzer2 and plugins configuration..."
        _reset_t2_config
    fi

    #printinf "Cleaning temporary files"
    for ((i=0; i < ${#QUERIES[*]}; i+=4)); do
        rm -f ${QUERIES[$((i+3))]}
    done

    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
}

################################################################################
# LaTeX formatting functions
################################################################################

# $1: number of columns
# $2: text, e.g., N/A: nDPI plugin required
_to_tex_table_empty() {
    $TAWK -v num_cols="$1" '{
        mid = n/2 - 1
        for (i = 0; i < n; i++) {
            printf "\\rowcolor{\\altrowcoloreven}"
            if (i == mid) {
                printf "\\multicolumn{%s}{c}{%s}\\\\\n", num_cols, texscape($0)
            } else {
                for (j = 1; j < num_cols; j++) {
                    printf "&"
                }
                print "\\\\"
            }
        }
    }' <<< "$2"
}

# $1: field name (No 'field name' detected)
_to_tex_table_str_num() {
    if [ -z "$1" ]; then
        printerr "Usage: _to_tex_table_str_num field_name"
        exit 1
    fi
    $TAWK -v field_name="$1" '
        NR > n {
            printf "%%"
        }
        {
            print texscape($1) " & " hrnum($2, hrnum_mode) "\\\\"
        }
        END {
            if (NR >= 1) {
                for (i = NR; i < n; i++) {
                    print "\\rowcolor{\\altrowcoloreven}&\\\\"
                }
            } else {
                mid = n/2 - 1
                for (i = 0; i < n; i++) {
                    printf "\\rowcolor{\\altrowcoloreven}"
                    if (i == mid) {
                        printf "\\multicolumn{2}{c}{No %s detected}\\\\\n", field_name
                    } else {
                        print "&\\\\"
                    }
                }
            }
        }'
}

# $1: field name (No 'field name' detected)
_to_tex_table_str_str_num() {
    if [ -z "$1" ]; then
        printerr "Usage: _to_tex_table_str_str_num field_name"
        exit 1
    fi
    $TAWK -v field_name="$1" '
        NR > n {
            printf "%%"
        }
        {
            print texscape($1) " & " texscape($2) " & " hrnum($3, hrnum_mode) "\\\\"
        }
        END {
            if (NR >= 1) {
                for (i = NR; i < n; i++) {
                    print "\\rowcolor{\\altrowcoloreven}&&\\\\"
                }
            } else {
                mid = n/2 - 1
                for (i = 0; i < n; i++) {
                    printf "\\rowcolor{\\altrowcoloreven}"
                    if (i == mid) {
                        printf "\\multicolumn{3}{c}{No %s detected}\\\\\n", field_name
                    } else {
                        print "&&\\\\"
                    }
                }
            }
        }'
}

# $1: ignored
_to_tex_table_non_std_ports() {
    $TAWK '
        {
            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 (NR < 1) {
                mid = n/2 - 1
                for (i = 0; i < n; i++) {
                    printf "\\rowcolor{\\altrowcoloreven}"
                    if (i == mid) {
                        printf "\\multicolumn{5}{c}{No protocols over non-standard ports detected}\\\\\n"
                    } else {
                        print "&&&&\\\\"
                    }
                }
            }
        }'
}

# $1: ignored
_to_tex_table_passwords() {
    $TAWK -v hideuser="$HIDEUSER" -v hidepass="$HIDEPASS" '
        BEGIN {
            tabhdr = sprintf("\\begin{longtable}{*{5}{l}r}\n\\toprule\\rowcolor{\\altrowcoloreven}")
            l = split("Client,Server,Proto,Username,Password,Flows", h, ",")
            for (i = 1; i < l; i++) tabhdr = tabhdr "\n" sprintf("{\\bf %s} & ", h[i])
            tabhdr = tabhdr "\n" sprintf("{\\bf %s}\\\\\n\\midrule\\endhead%\n", h[i])
        }
        {
            # ignore empty username and passwords
            if ((strisempty($4) && strisempty($5)) ||
                (streq($4, "(null)") && streq($5, "(null)")))
            {
                next
            }
            if (tabhdr) {
                print tabhdr
                tabhdr = ""
            }
            # obfuscate user/pass if required
            if (hideuser) $4 = "********"
            if (hidepass) $5 = "********"
            if (NR > n) printf "%%"
            for (i = 1; i < NF; i++) printf "%s & ", texscape(unquote($i))
            printf "%s\\\\\n", hrnum($NF, hrnum_mode)
        }
        END {
            if (tabhdr) printf "No cleartext passwords detected\n"
            else printf "\\bottomrule\n\\end{longtable}\n"
        }'
}

# $1: ignored
_to_tex_table_exe() {
    $TAWK '
        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 "\\toprule"
            #print "\\begin{longtable}{llllll}"
            #print "\\toprule\\rowcolor{\\altrowcoloreven}"
            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) {
                printf "No EXE download detected"
            } else {
                print "\\bottomrule"
                #print "\\end{longtable}"
                print "\\end{tabularx}"
                print "\\end{center}"
                print "\\end{scriptsize}"
            }
        }'
}

# $1: ignored
_to_tex_table_arp() {
    sort -u | $TAWK '
        {
            _ip_mac[$2] = _ip_mac[$2] "\t" $1
        }
        END {
            for (_ip in _ip_mac) {
                _l = split(lstrip(_ip_mac[_ip]), _mac, "\t")
                if (_l > 1) {
                    print _ip OFS join(_mac, OFS)
                }
            }
        }' | $TAWK '
            NR == 1 {
                print "ARP spoofing detected for:"
                print "\\begin{multicols}{3}"
                print "\\begin{itemize}"
            }
            NR <= n+10 {
                if (NR > n) printf "%%"
                print "\\item " $1
                if (NR > n) printf "%%"
                print "    \\begin{itemize}"
                for (i = 2; i <= NF; i++) {
                    if (i > n || NR > n) printf "%%"
                    print "    \\item " $i
                }
                if (NR > n) printf "%%"
                print "    \\end{itemize}"
                next
            }
            NR > n+10 {
                exit
            }
            END {
                if (NR == 0) {
                    print "No ARP spoofing detected"
                } else {
                    print "\\end{itemize}"
                    print "\\end{multicols}"
                }
            }'
}

# $1: ignored
_to_tex_table_dns_zt() {
    $TAWK '
        NR == 1 {
            print "\\begin{longtable}{llll}"
            print "\\toprule\\rowcolor{\\altrowcoloreven}"
            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"
        }'
}

# $1: ignored
_to_tex_table_ssh() {
    $TAWK 't2sort(5, 0, "num")' | $TAWK '
        NR == 1 {
            tabhdr = tabhdr "\\begin{tabularx}{\\textwidth}{*{5}{l}L}\n\\toprule"
            l = split("DateFirstSeen,Duration,srcIP,dstIP,SBytes,sshVersion", h, ",")
            for (i = 1; i < l; i++) tabhdr = tabhdr "\n" sprintf("{\\bf %s} &", h[i])
            tabhdr = tabhdr sprintf("{\\bf %s}\\\\\n\\midrule\n%\\endhead%\n", h[i])
            print tabhdr
        }
        {
            if (NR > n) printf "%%"
            # DateFirstSeen
            gsub(/\.[0-9]+/, "", $1) # ignore microseconds
            printf "%s & ", utc($1)
            # Duration
            gsub(/^00:(00:)?0?/, "", $2) # ignore leading zeroes
            for (i = 2; i < NF-1; i++) {
                printf "%s & ", $i # Duration, srcIP, dstIP
            }
            printf "%s & ", hrnum($(NF-1), hrnum_mode) # SBytes
            printf "%s\\\\\n", texscape(unquote($NF))  # sshVersion
        }
        END {
            if (NR == 0) {
                print "No SSH connection detected"
            } else {
                print "\\bottomrule"
                print "\\end{tabularx}"
            }
        }'
}

# $1: ignored
_to_tex_chart() {
    AWK -v n="$CHART_N" '  # Overwrite n=$TABLE_N
        {
            a[NR, "name"] = $1
            a[NR, "count"] = $2
        }
        END {
            vmax = NR < n ? NR : n
            for (i = 1; i < vmax; i++) {
                printf "%s,", a[i, "name"]
            }
            printf "%s}]\n", a[i, "name"]
            print "\\addplot[fill=\\chartcolor] coordinates {"
            for (i = 1; i <= vmax; i++) {
                printf "(%s,%s)\n", a[i, "name"], a[i, "count"]
            }
        }'
}

# $1: ignored
_to_tex_proto_chart() {
    $TAWK '{ print proto2str($1), $2 }' | _to_tex_chart "$1"
}

################################################################################
# Setup functions
################################################################################

_setup_clickhouse() {
    DBTYPE="ClickHouse"
    SCRIPTS="$T2FMDIR/clickhouse"
    if [ "$(uname)" = "Darwin" ]; then
        CMD=(clickhouse client)
    else
        CMD=(clickhouse-client)
    fi

    local databases
    if ! databases="$("${CMD[@]}" -q 'SHOW DATABASES' 2> /dev/null)"; then
        printerr "$DBTYPE server is not running"
        exit 1
    fi

    if ! grep "^${DBNAME}$" <<< "${databases[@]}" &> /dev/null; then
        printerr "$DBTYPE database '$DBNAME' not found"
        exit 1
    fi

    CMD+=(-d "$DBNAME")

    if ! "${CMD[@]}" -q 'SHOW TABLES' | grep -Fw flow &> /dev/null; then
        printerr "$DBTYPE table 'flow' not found in database '$DBNAME'"
        exit 1
    fi

    if [[ "$("${CMD[@]}" -q 'SELECT COUNT(*) FROM flow')" -eq 0 ]]; then
        printerr "$DBTYPE table 'flow' from database '$DBNAME' is empty"
        exit 1
    fi

    COLS="$("${CMD[@]}" -q 'DESC TABLE flow' | cut -f 1)"

    if [ -z "$TIME_FROM" ]; then
        TIME_FROM="$("${CMD[@]}" --queries-file "$SCRIPTS/min_time")"
    fi

    if [ -z "$TIME_TO" ]; then
        TIME_TO="$("${CMD[@]}" --queries-file "$SCRIPTS/max_time")"
    fi

    CMD+=(
        --param_n="$TOP_N"
        --param_time_from="$TIME_FROM"
        --param_time_to="$TIME_TO"
        --queries-file
    )
}

_setup_mongo() {
    DBTYPE="MongoDB"
    SCRIPTS="$T2FMDIR/mongo"
    CMD=(mongosh --quiet "$DBNAME")

    if ! "${CMD[@]}" --eval 'db.getName()' &> /dev/null; then
        printerr "$DBTYPE server is not running"
        exit 1
    fi

    if [[ "$("${CMD[@]}" --eval 'db.flow.countDocuments()')" -eq 0 ]]; then
        printerr "$DBTYPE collection 'flow' from database '$DBNAME' is empty"
        exit 1
    fi

    # XXX this assumes all fields are present in the first row
    COLS="$("${CMD[@]}" --eval 'const row = db.flow.findOne(); for (var key in row) print(key)')"

    if [ -z "$TIME_FROM" ]; then
        TIME_FROM="$("${CMD[@]}" "$SCRIPTS/min_time")"
        TIME_FROM_MONGO="$($TAWK '{ print utc($1) }' <<< "$TIME_FROM")"
    fi

    if [ -z "$TIME_TO" ]; then
        TIME_TO="$("${CMD[@]}" "$SCRIPTS/max_time")"
        TIME_TO_MONGO="$($TAWK '{ print utc($1) }' <<< "$TIME_TO")"
    fi

    CMD+=(
        --eval "const n = $TOP_N, \
                      time_from = new ISODate('$TIME_FROM_MONGO'), \
                      time_to = new ISODate('$TIME_TO_MONGO');"
    )
}

_setup_psql() {
    DBTYPE="PostgreSQL"
    SCRIPTS="$T2FMDIR/psql"
    CMD=(psql -U postgres)

    local databases
    if ! databases="$("${CMD[@]}" -l 2> /dev/null)"; then
        printerr "$DBTYPE server is not running"
        exit 1
    fi

    if [ -z "$(AWK -F'|' "\$1 ~ /^\s*$DBNAME\s*$/" <<< "$databases")" ]; then
        printerr "$DBTYPE database '$DBNAME' not found"
        exit 1
    fi

    CMD+=(-d "$DBNAME" -A)

    if ! "${CMD[@]}" -c 'SELECT "tablename" FROM pg_catalog.pg_tables' | grep -Fw flow &> /dev/null; then
        printerr "$DBTYPE table 'flow' not found in database '$DBNAME'"
        exit 1
    fi

    if [[ "$("${CMD[@]}" -t -c 'SELECT COUNT(*) FROM flow')" -eq 0 ]]; then
        printerr "$DBTYPE table 'flow' from database '$DBNAME' is empty"
        exit 1
    fi

    COLS="$("${CMD[@]}" -c 'SELECT * FROM flow LIMIT 0' | head -1)"

    CMD+=(-t -F $'\t')

    if [ -z "$TIME_FROM" ]; then
        TIME_FROM="$("${CMD[@]}" -f "$SCRIPTS/min_time")"
    fi

    if [ -z "$TIME_TO" ]; then
        TIME_TO="$("${CMD[@]}" -f "$SCRIPTS/max_time")"
    fi

    CMD+=(
        -v n="$TOP_N"
        -v time_from="$TIME_FROM"
        -v time_to="$TIME_TO"
        -f
    )
}

_setup_tawk() {
    SCRIPTS="$T2FMDIR/tawk"
    COLS="$($TAWK -l "$FLOWFILE")"
    CMD=($TAWK -I "$FLOWFILE" -v n="$TOP_N" -f)
}

################################################################################
# Main: Program entry point
################################################################################

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

while [ $# -gt 0 ]; do
    case "$1" in
        -b|--build)
            BUILD_T2=1
            ;;
        --reset)
            RESET=1
            ;;
        -A|--open-pdf)
            OPENPDF=1
            ;;
        -T)
            validate_next_arg "$1" "$2"
            validate_next_arg "$1" "$3"
            TIME_FROM="$($TAWK '{ print timestamp($1) }' <<< "$2")"
            TIME_TO="$($TAWK '{ print timestamp($1) }' <<< "$3")"
            shift  # TIME_FROM
            shift  # TIME_TO
            ;;
        -f|--hash-factor)
            validate_next_num "$1" "$2"
            HASHFACTOR="-f $2"
            shift
            ;;
        -c|--clickhouse)
            validate_next_arg "$1" "$2"
            CLICKHOUSEDB="$2"
            shift
            ;;
        -m|--mongo)
            validate_next_arg "$1" "$2"
            MONGODB="$2"
            shift
            ;;
        -p|--postgres)
            validate_next_arg "$1" "$2"
            PSQLDB="$2"
            shift
            ;;
        -i|--iface)
            validate_next_arg "$1" "$2"
            IFACE="$2"
            shift
            ;;
        -r|--pcap)
            validate_next_pcap "$1" "$2"
            PCAP="$2"
            shift
            ;;
        -R|--pcap-list)
            validate_next_file "$1" "$2"
            PCAPLIST="$2"
            shift
            ;;
        -F|--flow-file)
            validate_next_file "$1" "$2"
            FLOWFILE="$2"
            shift
            ;;
        -w|--output-prefix)
            validate_next_arg "$1" "$2"
            OPREF="$2"
            shift
            ;;
        --hide-user)
            HIDEUSER=1
            ;;
        --hide-pass)
            HIDEPASS=1
            ;;
        --hide-user-pass)
            HIDEUSER=1
            HIDEPASS=1
            ;;
        --no-countries)
            NOCOUNTRIES=1
            ;;
        --no-organisations)
            NOORGANISATIONS=1
            ;;
        --no-dns)
            NODNS=1
            ;;
        --no-http)
            NOHTTP=1
            ;;
        --no-https)
            NOHTTPS=1
            ;;
        --no-ssh)
            NOSSH=1
            ;;
        --no-non-std-ports)
            NONONSTDPORTS=1
            ;;
        --no-passwords)
            NOPASSWORDS=1
            ;;
        --no-warnings)
            NOWARNINGS=1
            ;;
        -C|--color)
            validate_next_arg "$1" "$2"
            COLOR="$2"
            shift
            ;;
        -L|--no-log-axis)
            LOGAXIS=0
            ;;
        --copyright)
            SHOW_COPYRIGHT=1
            if [ "$2" ] && ! arg_is_option "$2"; then
                COPYRIGHT="$2"
                shift
            fi
            ;;
        --watermark)
            SHOW_WATERMARK=1
            if [ "$2" ] && ! arg_is_option "$2"; then
                WATERMARK="$2"
                shift
            fi
            ;;
        -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
            ;;
        -c|--chart-n)
            validate_next_num "$1" "$2"
            CHART_N="$2"
            shift
            ;;
        -H|--raw-numbers)
            HRNUM=2
            ;;
        -HH|--raw-and-hrnum)
            HRNUM=1
            ;;
        -[0-9]|-[1-9][0-9]*)
            NCPUS="${1#*-}"
            ;;
        -y|--yes)
            YES="yes"
            ;;
        -\?|-h|--help)
            usage
            exit 0
            ;;
        *)
            abort_option_unknown "$1"
            ;;
    esac
    shift
done

TAWK="$TAWK -v n=$TABLE_N -v hrnum_mode=$HRNUM"

DBNAME="$CLICKHOUSEDB$MONGODB$PSQLDB"
INFILE="$FLOWFILE$PCAP$PCAPLIST"
INPUT="$IFACE$INFILE$DBNAME"

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

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

# Check for required programs

check_dependency pdflatex

case "$INPUT" in
    "$CLICKHOUSEDB")
        if [ "$(uname)" = "Darwin" ]; then
            check_dependency clickhouse
        else
            check_dependency clickhouse-client
        fi
        ;;
    "$MONGODB")
        check_dependency mongosh
        ;;
    "$PSQLDB")
        check_dependency psql
        ;;
esac

if [ -z "$NCPUS" ]; then
    NCPUS=$(get_nproc)
fi

_set_odir_opref

if [ ! -d "$ODIR" ]; then
    ask_default_yes "Output folder '$ODIR' does not exist... create it" "$YES" || exit 1
    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 "$FLOWFILE" ]; then
    HDRFILE="$($SED 's/_flows.txt/_headers.txt/' <<< "$FLOWFILE")"
    if [ ! -f "$HDRFILE" ]; then
        printwrn "Header file not found"
    else
        CMDLINE="$(grep -F 'Command line: ' "$HDRFILE")"
        if [ -n "$(grep -F -- -r <<< "$CMDLINE")" ]; then
            PCAP="$(perl -pe 's/.*-r\s+([^[:space:]]+)\s+.*$/\1/'<<< "$CMDLINE")"
        fi
    fi
elif [ -z "$DBNAME" ]; then

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

    _check_t2_plugins

    if [ ! -x "$(get_t2_exec)" ]; then
        printerr "Tranalyzer executable not found"
        printinf "Try using $SNAME -b option"
        exit 1
    fi

    PREFIX="$($READLINK -f "$ODIR/$OPREF")"
    # Handle the special case where OPREF was extracted from
    # INPUT and a folder with the same name exists
    if [ -d "$PREFIX" ]; then
        _PREFIX="$PREFIX/$OPREF"
    else
        _PREFIX="$PREFIX"
    fi
    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"
        ask_default_no "Try to generate the report anyway" "$YES" || exit 1
    fi

    printinf "Generating report..."
fi

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

# TODO query a bit more than required (will be commented out in the report)
TOP_N="$(($TABLE_N > $CHART_N ? $TABLE_N : $CHART_N))"

if [ -n "$CLICKHOUSEDB" ]; then
    _setup_clickhouse
elif [ -n "$MONGODB" ]; then
    _setup_mongo
elif [ -n "$PSQLDB" ]; then
    _setup_psql
else
    _setup_tawk
fi

_check_colnames "$COLS"

# Build output filename
OFILE="$($READLINK -f "$ODIR/${OPREF}.tex")"
PDFFILE="$($SED 's/\.tex/.pdf/' <<< "$OFILE")"

# Copy the template
cp "$T2FMDIR/t2fm_template.tex" "$OFILE"

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

################################################################################
# Functions to delete/replace LaTeX code
################################################################################

# $1: name, e.g., DNS for __BEGIN_DNS__, __END_DNS__
_delete_begin_end() {
    if [ -z "$1" ]; then
        printerr "Usage: _delete_begin_end name"
        exit 1
    fi
    $SED -i "/%__BEGIN_${1}__/,/%__END_${1}__/d" "$OFILE"
}

# $1: placeholder name
# $2: replacement text
_replace_placeholder() {
    if [ -z "$1" ]; then
        printerr "Usage: _replace_placeholder name text"
        exit 1
    fi
    $SED -i "s|%%__${1}__%%|${2}|g" "$OFILE"
}

# $1: plugin name
_insert_plugin_required() {
    if [ -z "$1" ]; then
        printerr "Usage: _insert_plugin_required pluginName"
        exit 1
    fi
    local pName="$1"
    local pNameUpper="$(tr '[a-z]' '[A-Z]' <<< "$1")"
    local marker="${pNameUpper}_REQUIRED"
    $SED -i "s;\(%__BEGIN_${marker}__\);N/A: $pName plugin required\n\1;" "$OFILE"
    _delete_begin_end "${marker}"
}

################################################################################
# Remove unnecessary/unwanted sections
################################################################################

# Summary (DB or FILE)
if [ -n "$DBNAME" ]; then
    _delete_begin_end "FILE_REQUIRED"
else
    _delete_begin_end "DB_REQUIRED"
fi

[ "$NOCOUNTRIES" ]     && _delete_begin_end "COUNTRIES"
[ "$NOORGANISATIONS" ] && _delete_begin_end "ORGANISATIONS"
[ "$NODNS" ]           && _delete_begin_end "DNS"
[ "$NOHTTP" ]          && _delete_begin_end "HTTP"
[ "$NOHTTPS" ]         && _delete_begin_end "HTTPS"
[ "$NOSSH" ]           && _delete_begin_end "SSH"
[ "$NONONSTDPORTS" ]   && _delete_begin_end "NON_STD_PORTS"
[ "$NOPASSWORDS" ]     && _delete_begin_end "PASSWORDS"
[ "$NOWARNINGS" ]      && _delete_begin_end "WARNINGS"

################################################################################
# Check for optional plugins and insert 'plugin required' message
################################################################################

# arpDecode
if [ -z "$NOWARNINGS" ] && [ -z "$(grep -Fw arpStat <<< "$COLS")" ]; then
    NOARPDECODE=1
    _insert_plugin_required "arpDecode"
fi

# dnsDecode
if [ -z "$NODNS" ] && [ -z "$(grep -Fw dnsStat <<< "$COLS")" ]; then
    NODNS=1
    _insert_plugin_required "dnsDecode"
fi

# httpSniffer
if [ -z "$NOHTTP" ] && [ -z "$(grep -Fw httpStat <<< "$COLS")" ]; then
    NOHTTP=1
    _insert_plugin_required "httpSniffer"
fi

# nDPI
if [ -z "$(grep -Fw nDPIclass <<< "$COLS")" ]; then
    NONDPI=1
    X=$(mktemp)
    echo "$(_to_tex_table_empty 2 "N/A: nDPI plugin required")" > $X
    $SED -i "/%%__top_appl_flows__%%/r$X" "$OFILE"
    $SED -i "/%%__top_appl_pkts__%%/r$X"  "$OFILE"
    $SED -i "/%%__top_appl_bytes__%%/r$X" "$OFILE"
    rm "$X"
fi

# portClassifier
if [ -z "$(grep -E "\<dstPortClassN?\>" <<< "$COLS")" ]; then
    NOPORTCLASSIFIER=1
    _insert_plugin_required "portClassifier"
fi

# nDPI and portClassifier
if [ -z "$NONONSTDPORTS" ]; then
    if [ -n "$NONDPI" ] || [ -n "$NOPORTCLASSIFIER" ]; then
        $SED -i "s;\(%__BEGIN_NDPI_AND_PORTCLASSIFIER_REQUIRED__\);N/A: nDPI and portClassifier plugins required\n\1;" "$OFILE"
        _delete_begin_end "NDPI_AND_PORTCLASSIFIER_REQUIRED"
        NONONSTDPORTS=1
    fi
fi

# pwX
if [ -z "$NOPASSWORDS" ] && [ -z "$(grep -Fw pwxType <<< "$COLS")" ]; then
    NOPASSWORDS=1
    _insert_plugin_required "pwX"
fi

# sshDecode
if [ -z "$NOSSH" ] && [ -z "$(grep -Fw sshStat <<< "$COLS")" ]; then
    NOSSH=1
    _insert_plugin_required "sshDecode"
fi

# sslDecode
if [ -z "$NOHTTPS" ] && [ -z "$(grep -Fw sslStat <<< "$COLS")" ]; then
    NOHTTPS=1
    _insert_plugin_required "sslDecode"
fi

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

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

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

if [ -n "$DBNAME" ]; then
    FILENAME="$DBNAME"
    FULLNAME="$FILENAME"
    PERIOD="$($TAWK -F, '{ print utc($1) " -- " utc($2) }' <<< "$TIME_FROM,$TIME_TO")"
elif [ -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 -q "$PCAP" > $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
################################################################################

"${CMD[@]}" "$SCRIPTS/summary" | $TAWK '{
    pkts  = ($3 ? $3 : 0)
    bytes = ($4 ? $4 : 0)
    print $1, $2, $2 - $1, hrnum(pkts, 1), hrnum(bytes, 1)
}' > $FIRST_LAST_DUR_NPKTS_NBYTES &

HOSTS="$("${CMD[@]}" "$SCRIPTS/unique_ips")"

if [ -z "$HOSTS" ]; then
    DISTINCTIP=0
    DISTINCTPRIVIP=0
    DISTINCTPUBIP=0
    DISTINCTIP4=0
    DISTINCTIP6=0
else
    DISTINCTIP="$(wc -l <<< "$HOSTS" | $TAWK '{ print hrnum(strip($1), 1) }')"
    DISTINCTPRIVIP="$($TAWK -v i=0 'privip($1) { i++ } END { print hrnum(i ? i : 0, 1) }' <<< "$HOSTS")"
    DISTINCTPUBIP="$($TAWK -v i=0 '!privip($1) { i++ } END { print hrnum(i ? i : 0, 1) }' <<< "$HOSTS")"
    DISTINCTIP6="$($TAWK -v i=0 '/:/ { i++ } END { print hrnum(i ? i : 0, 1) }' <<< "$HOSTS")"
    DISTINCTIP4="$($TAWK '{ print hrnum($1 - $2, 1) }' <<< "$DISTINCTIP\t$DISTINCTIP6")"
fi

QUERY_SCRIPT=0
QUERY_FORMAT=1
QUERY_NAME=2
QUERY_TEMP=3

_add_query() {
    if [ ! "$3" ]; then
        printerr "Usage: _add_query script_name formatting_function text"
        exit 1
    fi
    QUERIES+=(
        "$1" "$2" "$3" $(mktemp)
    )
}

QUERIES=()

# Top source IP addresses
_add_query "top_srcIP_flows" _to_tex_table_str_str_num "Source IP"
_add_query "top_srcIP_pkts"  _to_tex_table_str_str_num "Source IP"
_add_query "top_srcIP_bytes" _to_tex_table_str_str_num "Source IP"

# Top destination IP addresses
_add_query "top_dstIP_flows" _to_tex_table_str_str_num "Destination IP"
_add_query "top_dstIP_pkts"  _to_tex_table_str_str_num "Destination IP"
_add_query "top_dstIP_bytes" _to_tex_table_str_str_num "Destination IP"

# Top TCP source ports
_add_query "top_tcp_srcPort_flows" _to_tex_chart "TCP Source Port"
_add_query "top_tcp_srcPort_pkts"  _to_tex_chart "TCP Source Port"
_add_query "top_tcp_srcPort_bytes" _to_tex_chart "TCP Source Port"

# Top TCP destination ports
_add_query "top_tcp_dstPort_flows" _to_tex_chart "TCP Destination Port"
_add_query "top_tcp_dstPort_pkts"  _to_tex_chart "TCP Destination Port"
_add_query "top_tcp_dstPort_bytes" _to_tex_chart "TCP Destination Port"

# Top UDP source ports
_add_query "top_udp_srcPort_flows" _to_tex_chart "UDP Source PORT"
_add_query "top_udp_srcPort_pkts"  _to_tex_chart "UDP Source PORT"
_add_query "top_udp_srcPort_bytes" _to_tex_chart "UDP Source PORT"

# Top UDP destination ports
_add_query "top_udp_dstPort_flows" _to_tex_chart "UDP Destination PORT"
_add_query "top_udp_dstPort_pkts"  _to_tex_chart "UDP Destination PORT"
_add_query "top_udp_dstPort_bytes" _to_tex_chart "UDP Destination PORT"

# Top protocols
_add_query "top_proto_flows" _to_tex_proto_chart "Protocols"
_add_query "top_proto_pkts"  _to_tex_proto_chart "Protocols"
_add_query "top_proto_bytes" _to_tex_proto_chart "Protocols"

# Top source and destination IP countries (require basicFlow or geoip)
if [ -z "$NOCOUNTRIES" ]; then
    # Top source IP countries (require basicFlow or geoip)
    _add_query "top_srcCC_flows" _to_tex_table_str_num "Source IP"
    _add_query "top_srcCC_pkts"  _to_tex_table_str_num "Source IP"
    _add_query "top_srcCC_bytes" _to_tex_table_str_num "Source IP"

    # Top destination IP countries (require basicFlow or geoip)
    _add_query "top_dstCC_flows" _to_tex_table_str_num "Destination IP"
    _add_query "top_dstCC_pkts"  _to_tex_table_str_num "Destination IP"
    _add_query "top_dstCC_bytes" _to_tex_table_str_num "Destination IP"
fi

# Top source and destination IP organisations (require basicFlow)
if [ -z "$NOORGANISATIONS" ]; then
    # Top source IP organisations (require basicFlow)
    _add_query "top_srcOrg_flows" _to_tex_table_str_num "Source IP"
    _add_query "top_srcOrg_pkts"  _to_tex_table_str_num "Source IP"
    _add_query "top_srcOrg_bytes" _to_tex_table_str_num "Source IP"

    # Top destination IP organisations (require basicFlow)
    _add_query "top_dstOrg_flows" _to_tex_table_str_num "Destination IP"
    _add_query "top_dstOrg_pkts"  _to_tex_table_str_num "Destination IP"
    _add_query "top_dstOrg_bytes" _to_tex_table_str_num "Destination IP"
fi

# Top Applications (require nDPI)
if [ -z "$NONDPI" ]; then
    _add_query "top_appl_flows" _to_tex_table_str_num "application"
    _add_query "top_appl_pkts"  _to_tex_table_str_num "application"
    _add_query "top_appl_bytes" _to_tex_table_str_num "application"
fi

# Top protocols over non-standard ports
if [ -z "$NONONSTDPORTS" ]; then
    _add_query "top_proto_over_nonstd_ports" _to_tex_table_non_std_ports "protocols over non-standard ports"
fi

# Cleartext passwords
if [ -z "$NOPASSWORDS" ]; then
    _add_query "top_passwords" _to_tex_table_passwords "cleartext passwords"
fi

# DNS (require dnsDecode)
if [ -z "$NODNS" ]; then
    _add_query "top_dns_queries" _to_tex_table_str_num "DNS query"
    _add_query "top_dns_answers" _to_tex_table_str_num "DNS answer"
    _add_query "top_dns_ipv4"    _to_tex_table_str_num "DNS IPv4 address"
    _add_query "top_dns_ipv6"    _to_tex_table_str_num "DNS IPv6 address"
    _add_query "top_dns_tld"     _to_tex_table_str_num "DNS query"
    _add_query "top_dns_sld"     _to_tex_table_str_num "DNS query"
fi

# HTTP (require httpSniffer)
if [ -z "$NOHTTP" ]; then
    _add_query "top_http_user_agent"      _to_tex_table_str_num "HTTP User-Agent"
    _add_query "top_http_host"            _to_tex_table_str_num "HTTP Host"
    _add_query "top_http_server"          _to_tex_table_str_num "HTTP Server"
    _add_query "top_http_content_type"    _to_tex_table_str_num "HTTP Content-Type"
    _add_query "top_http_content_subtype" _to_tex_table_str_num "HTTP Content-Type"
    _add_query "top_http_rscode"          _to_tex_chart         "HTTP Status"
fi

# HTTPS (require sslDecode)
if [ -z "$NOHTTPS" ]; then
    _add_query "top_https_sni"         _to_tex_table_str_num     "HTTPS SNI"
    _add_query "top_https_cert_cn"     _to_tex_table_str_num     "HTTPS certificate Common Name"
    #_add_query "top_https_cert_issuer" _to_tex_table_str_num     "HTTPS certificate Issuer"
    #_add_query "top_https_cert_bl"     _to_tex_table_str_num     "HTTPS certificate fingerprint"
    _add_query "top_https_ja3_known"   _to_tex_table_str_str_num "known HTTPS JA3 signature"
    #_add_query "top_https_ja3"         _to_tex_table_str_str_num "HTTPS JA3 signature"
    #_add_query "top_https_ja3_unknown" _to_tex_table_str_num     "HTTPS JA3 signature"
fi

# SSH (require sshDecode)
if [ -z "$NOSSH" ]; then
    _add_query "ssh"             _to_tex_table_ssh         "SSH connections"
    _add_query "top_hassh_known" _to_tex_table_str_str_num "known HASSH signature"
fi

# Warnings
if [ -z "$NOWARNINGS" ]; then
    # EXE downloads
    if [ -z "$NOHTTP" ]; then
        if [ -n "$DBNAME" ]; then
            _replace_placeholder "top_exe_dl" "N/A: EXE downloads detection not implemented in DB backends yet"
        else
            _add_query "top_exe_dl" _to_tex_table_exe "EXE"
        fi
    fi

    # ARP spoofing
    if [ -z "$NOARPDECODE" ]; then
        _add_query "arp_spoofing" _to_tex_table_arp "ARP"
    fi

    # DNS zone transfer
    if [ -z "$NODNS" ]; then
        _add_query "dns_zone_transfer" _to_tex_table_dns_zt "DNS ZT"
    fi
fi

for ((i=0; i < ${#QUERIES[*]}; i+=4)); do
    if [ -f "$SCRIPTS/${QUERIES[$i]}" ]; then
        "${CMD[@]}" "$SCRIPTS/${QUERIES[$i]}" | "${QUERIES[$((i+1))]}" "${QUERIES[$((i+2))]}" > "${QUERIES[$((i+3))]}" &
    else
        TEXT="$($TAWK '{ print "N/A: " $0 " script not found" }' <<< "$(basename "$SCRIPTS/${QUERIES[$i]}")")"
        case "${QUERIES[$((i+1))]}" in
            _to_tex_table_str_num)       NCOLS=2;;
            _to_tex_table_str_str_num)   NCOLS=3;;
            _to_tex_table_dns_zt)        NCOLS=4;;
            _to_tex_table_non_std_ports) NCOLS=5;;
            _to_tex_table_passwords)     NCOLS=6;;
            _to_tex_table_exe)           NCOLS=6;;
            _to_tex_table_ssh)           NCOLS=6;;
            #_to_tex_table_arp)                  ;; # Not really a table
        esac
        [ -n "$NCOLS" ] && TEXT="$(_to_tex_table_empty $NCOLS "$TEXT")"
        echo "$TEXT" > "${QUERIES[$((i+3))]}"
    fi
    # test for CPU usage
    if [ $NCPUS -eq 1 ]; then
        wait
    elif [ $NCPUS -gt 0 ] && [ $POLLINT -gt 0 ]; then
        # Wait for one CPU to be free
        NPROC=$(jobs -p | wc -l)
        while [ $NPROC -eq $NCPUS ]; do
            sleep $POLLINT
            NPROC=$(jobs -p | wc -l)
        done
    fi
done

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

wait < <(jobs -p)

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

FILENAME="$($TAWK '{ print texscape($0) }' <<< "$FILENAME" | $SED 's/\\/\\\\/g')"
FULLNAME="$($TAWK '{ print texscape($0) }' <<< "$FULLNAME" | $SED 's/\\/\\\\/g')"
COPYRIGHT="$($TAWK '{ print texscape($0) }' <<< "$COPYRIGHT" | $SED 's/\\/\\\\/g')"
WATERMARK="$($TAWK '{ print texscape($0) }' <<< "$WATERMARK" | $SED 's/\\/\\\\/g')"
FIRST="$(AWK -F'\t' '{ print $1 }' $FIRST_LAST_DUR_NPKTS_NBYTES)"
LAST="$(AWK -F'\t' '{ print $2 }' $FIRST_LAST_DUR_NPKTS_NBYTES)"
DURATION="$(AWK -F'\t' '{ print $3 }' $FIRST_LAST_DUR_NPKTS_NBYTES)"
NUMPKTS="$(AWK -F'\t' '{ print $4 }' $FIRST_LAST_DUR_NPKTS_NBYTES)"
NUMBYTES="$(AWK -F'\t' '{ print $5 }' $FIRST_LAST_DUR_NPKTS_NBYTES)"
if [ -z "$FIRST" ] || [ -z "$LAST" ]; then
    UTCFIRST="N/A"
    UTCLAST="N/A"
elif [ "$(uname)" != "Darwin" ]; then
    UTCFIRST="$(date -u -d @$FIRST)"
    UTCLAST="$(date -u -d @$LAST)"
else
    FIRST="$($SED 's/\.[0-9]*$//' <<< "$FIRST")"
    LAST="$($SED 's/\.[0-9]*$//' <<< "$LAST")"
    UTCFIRST="$(date -u -j -r $FIRST)"
    UTCLAST="$(date -u -j -r $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"

[ "$SHOW_COPYRIGHT" ] && $SED -i "s/copyrightfalse/copyrighttrue/" "$OFILE"
[ "$SHOW_WATERMARK" ] && $SED -i "s/watermarkfalse/watermarktrue/" "$OFILE"

[ -n "$PERIOD" ] && $SED -i "s;__PERIOD__;$PERIOD;" "$OFILE"
[ -n "$DBTYPE" ] && $SED -i "s/__DBTYPE__/$DBTYPE/" "$OFILE"

$SED -i "s/__CHART_COLOR__/$CHART_COLOR/"           "$OFILE"
$SED -i "s/__TABLE_ODD_COLOR__/$TABLE_ODD_COLOR/"   "$OFILE"
$SED -i "s/__TABLE_EVEN_COLOR__/$TABLE_EVEN_COLOR/" "$OFILE"

$SED -i "s/__AUTHOR__/$AUTHOR/"       "$OFILE"
$SED -i "s/__TITLE__/$TITLE/"         "$OFILE"
$SED -i "s/__COPYRIGHT__/$COPYRIGHT/" "$OFILE"
$SED -i "s/__WATERMARK__/$WATERMARK/" "$OFILE"
$SED -i "s/__TABLE_N__/$TABLE_N/g"    "$OFILE"
$SED -i "s/__CHART_N__/$CHART_N/g"    "$OFILE"

$SED -i "s;__FILENAME__;$FILENAME;"      "$OFILE"
$SED -i "s;__FULLNAME__;$FULLNAME;"      "$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/__NUMBYTES__/$NUMBYTES/" "$OFILE"

$SED -i "s/__DISTIP__/$DISTINCTIP/"     "$OFILE"
$SED -i "s/__PRIVIP__/$DISTINCTPRIVIP/" "$OFILE"
$SED -i "s/__PUBIP__/$DISTINCTPUBIP/"   "$OFILE"
$SED -i "s/__DISTIP4__/$DISTINCTIP4/"   "$OFILE"
$SED -i "s/__DISTIP6__/$DISTINCTIP6/"   "$OFILE"

for ((i=0; i < ${#QUERIES[*]}; i+=4)); do
    $SED -i "/%%__${QUERIES[$i]}__%%/r${QUERIES[$((i+3))]}" "$OFILE"
done

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

printok "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
