#!/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
#
# TODO
#   - Make sure dnsDecode, httpSniffer, nDPI and portClassifier are optional
#   - add link to virustotal for exe
#   - check for pdflatex (_check_dependencies_*)
#   - passwords: show/hide passwords
#   - use FILE_log.txt for more info (number of A, B, total flows, ...)

REQUIRED_PLUGINS=(
    #arpDecode
    basicFlow
    basicStats
    dnsDecode
    #geoip
    httpSniffer
    nDPI
    portClassifier
    #pwX
    #ssDecode
    txtSink
)

REQUIRED_COLS=(
    # arpDecode
    #arpStat

    # basicFlow
    dir
    flowStat
    UnixTimeFirst
    UnixTimeLast
    Duration
    SrcIP4
    DstIP4
    SrcPort
    DstPort
    L4Proto

    # basicStats
    numPktsSnt
    numPktsRcvd
    numBytesSnt
    numBytesRcvd

    # dnsDecode
    dnsAname
    dnsQname
    dnsStat
    dns4Aaddress
    dns6Aaddress

    # geoip
    #srcIpCountry

    # httpSniffer
    httpUsrAg
    httpHosts
    httpServ
    httpRSCode

    # nDPI
    nDPIclass

    # portClassifier
    dstPortClass
    dstPortClassN

    # pwX
    #extractedAuthType
    #extractedUsername
    #extractedPassword

    # ssDecode
    #sshVersion
)

#DEBUG=1

# Settings
CHART_N=5    # Number of values to display in charts
TABLE_N=5    # Number of values to display in tables
COLOR="cyan" # Charts color (cyan, red, orange, gray!25, ...)
LOGAXIS=1    # Whether to use logarithmic Y axis

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

SNAME="$(basename "$0")"

usage() {
    printf "Usage:\n"
    printf "    $SNAME [OPTION...] <FILE>\n\n"
    printf "Optional arguments:\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\n"
    printf "    -L                  Do not use logarithmic scale for axis\n"
    #printf "    -l                  Use logarithmic scale for axis\n"
    printf "    -n num              Compute top num statistics for tables\n"
    printf "    -m num              Compute top num statistics for charts\n\n"
    printf "    -?, -h, --help      Show help options and exit\n"
}

_printerr() {
    printf "\e[0;31m$1\e[0m\n" >&2  # Red
}

_printok() {
    printf "\e[0;32m$1\e[0m\n"      # Blue
}

_printinf() {
    printf "\e[0;34m$1\e[0m\n"      # Blue
}

_printwrn() {
    printf "\e[0;33m$1\e[0m\n"      # Orange
}

_abort_with_help() {
    printf "Try '$SNAME --help' for more information.\n"
    exit 1
}

# $1: name of the option
# $2: argument to validate
_validate_args() {
    if [ -n "$2" ] && [ "${2:0:1}" != "-" ]; then
        return 0
    else
        _printerr "Option '$1' requires an argument"
        _abort_with_help
    fi
}

# $1: name of the option
# $2: argument to validate
_validate_num() {
    if [ -n "$2" ] && [ -z "$(tr -d '[0-9]' <<< "$2")" ]; then
        return 0
    else
        _printerr "Invalid argument for option '$1': expected number; found '$2'"
        _abort_with_help
    fi
}

_check_plugins() {
    for i in ${REQUIRED_PLUGINS[@]}; do
        if [ -z "$(ls "$HOME/.tranalyzer/plugins/"[0-9][0-9][0-9]_${i}.so 2> /dev/null)" ]; then
            # TODO build plugin?
            _printerr "Plugin '$i' is required"
            exit 1
        fi
    done
}

_check_colnames() {
    for i in ${REQUIRED_COLS[@]}; do
        if [ -z "$($TAWK -l "$FILE" | grep "$i")" ]; then
            _printerr "Column '$i' not found."
            exit 1
        fi
    done
}

_check_dependencies_osx() {
    type gawk greadlink &> /dev/null || {
        local deps="coreutils gawk"
        _printerr "Missing dependencies: $deps"
        _printinf "You may use homebrew to install them: brew install coreutils"
        exit 1
    }

    AWK="$(which gawk)"
    READLINK="$(which greadlink)"
}

_check_dependencies_linux() {
    local deps="coreutils gawk"
    local pgrmname pgrmcmd
    type gawk readlink sed &> /dev/null || {
        if hash apt-get 2> /dev/null; then
            pgrmname="apt-get"
            pgrmcmd="apt-get install"
        elif hash pacman 2> /dev/null; then
            pgrmname="pacman"
            pgrmcmd="pacman -S"
        elif hash yum 2> /dev/null; then
            pgrmname="yum"
            pgrmcmd="yum install"
        else
            pgrmname="your package utility"
        fi
        [ -n "$pgrmcmd" ] && pgrmcmd=": $pgrmcmd $deps"
        _printerr "Missing dependencies: $deps"
        _printinf "You may use $pgrmname to install them$pgrmcmd"
        exit 1
    }

    local gver="$(gawk --version | awk '{print $3; exit}')"
    if [[ $gver < 4.1 ]]; then
        _printerr "Minimum gawk version required is 4.1, found '$gver'"
        exit 1
    fi

    AWK="$(which gawk)"
    READLINK="$(which readlink)"
}

_check_dependencies() {
    if [ "$(uname)" = "Darwin" ]; then
        _check_dependencies_osx
    else
        _check_dependencies_linux
    fi
}

_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
}

# Check for required programs
_check_dependencies

# Set T2HOME
if [ -n "$ZSH_VERSION" ]; then
    T2HOME="$(dirname "$($READLINK -f "${(%):-%x}")")"
else
    T2HOME="$(dirname "$($READLINK -f "$BASH_SOURCE")")"
fi
T2HOME="$($READLINK -f "$T2HOME/..")"

# Locate tawk
TAWK="$T2HOME/scripts/tawk/tawk"
if [ ! -f "$TAWK" ]; then
    _printerr "tawk script not found in '$T2HOME/scripts/tawk/'"
    exit 1
fi

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

while [ $# -gt 0 ]; do
    case $1 in
        -o|--output-folder)
            _validate_args "$1" "$2"
            ODIR="$2"
            shift
            ;;
        -w|--output-filename)
            _validate_args "$1" "$2"
            OPREF="$2"
            shift
            ;;
        -c|--color)
            _validate_args "$1" "$2"
            COLOR="$2"
            shift
            ;;
        -L|--no-log-axis) LOGAXIS=0;;
        #-l|--log-axis) LOGAXIS=1;;
        -a|--author)
            _validate_args "$1" "$2"
            AUTHOR="$2"
            shift
            ;;
        -t|--title)
            _validate_args "$1" "$2"
            TITLE="$2"
            shift
            ;;
        -n|--table-n)
            _validate_num "$1" "$2"
            TABLE_N="$2"
            shift
            ;;
        -m|--chart-n)
            _validate_num "$1" "$2"
            CHART_N="$2"
            shift
            ;;
        -\?|-h|--help) usage; exit 0;;
        *)
            if [ -f "$1" ]; then
                FILE="$1"
            fi
    esac
    shift
done

if [ ! -f "$FILE" ]; then
    _printerr "Input file is required"
    _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 "$(file -b "$FILE" | grep 'capture file')" ]; then
    # Locate tranalyzer
    T2="$T2HOME/tranalyzer2/src/tranalyzer"
    if [ ! -f "$T2" ]; then
        _printerr "tranalyzer not found in '$T2HOME/tranalyzer2/src/'"
        exit 1
    fi

    _check_plugins

    # Output folder
    if [ -z "$ODIR" ]; then
        ODIR="$(dirname "$FILE")"
    fi
    if [ -n "$OPREF" ]; then
        PREFIX="$OPREF"
    else
        PREFIX="$(basename "$FILE" | $TAWK -F'.' '{ $NF=""; printf "%s\n", chomp($0) }')"
    fi
    PREFIX="$ODIR/$PREFIX"

    PCAP="$FILE"
    FILE="$(awk '{ printf "%s_flows.txt\n", $0 }' <<< "$PREFIX")"
    _printinf "PCAP file provided... running Tranalyzer"
    $T2 -r "$PCAP" -w "$PREFIX" -l
    _printinf "Generating report..."
else
    HDR="$(sed 's/_flows.txt/_headers.txt/' <<< "$FILE")"
    if [ ! -f "$HDR" ]; then
        _printerr "Header file not found"
    else
        PCAP="$(grep 'Command line: ' "$HDR" | sed -r 's/.*-r\s+([^[:space:]]+)\s+.*$/\1/')"
    fi
fi

_check_colnames

trap "trap - SIGTERM && _cleanup 1" HUP INT QUIT TERM
trap "_cleanup 0" EXIT

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

# Temporary files

if [ -z "$DEBUG" ]; then

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

# 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 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)

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

fi # DEBUG

# File stat
if [ -f "$PCAP" ]; then
    FULLNAME="$PCAP" # $(sed 's/_/\\_/g' <<< "$PCAP")"
    FILENAME="$(sed -r 's/^.+\///' <<< "$FULLNAME")"
    FILESIZE="$(du -h "$PCAP" | awk '{ print $1 }')"
    [ -z "$DEBUG" ] && md5sum "$PCAP" | awk '{ print $1 }' > $MD5SUM &
else
    #_printwrn "PCAP file $PCAP not found"
    FULLNAME="N/A"
    FILENAME="$FILE" # $(sed 's/_/\\_/g' <<< "$FILE")"
    FILESIZE="N/A"
    [ -z "$DEBUG" ] && echo "N/A" > $MD5SUM
fi

if [ -z "$DEBUG" ]; then

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

$TAWK '!hdr() { t += $numPktsSnt } END { print t }' "$FILE" > $NUMPKTS &

# TODO parallel

# Time/Duration
FIRST="$($TAWK '!hdr() { print $UnixTimeFirst; exit }' "$FILE")"
LAST="$($TAWK '!hdr() { if (t < $UnixTimeLast) t = $UnixTimeLast } END { print t }' "$FILE")"
UTCFIRST="$(date -u -d @$FIRST)"
UTCLAST="$(date -u -d @$LAST)"
DURATION="$(awk -v l=$LAST -v f=$FIRST 'BEGIN { print l-f; exit }')"
DURSTR="$(awk -v s=$DURATION '
BEGIN {
    days     = int(s / 3600. / 24.)
    hours    = int(s / 3600. - days * 24)
    minutes  = int(s / 60. - hours * 60 - days * 24 * 60)
    seconds  = s % 60.
    if (days+hours+minutes) {
        printf "("
        if (days) printf "%s days ", days
        if (hours) printf "%s hours ", hours
        if (minutes) printf "%s minutes ", minutes
        if (seconds) printf "%s seconds", seconds
        printf ")\n"
    }
}')"

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

# Top Source/Destination IP addresses

#topSrcIP() {
#    if [ -z "$2" ]; then
#        echo "Usage: topSrcIP aggrval destfile"
#        exit 1
#    fi
#    $TAWK -v n="$TABLE_N" -v val="$1" '!hdr() && streq($dir, "A") && !bitisset($flowStat, 1) {
#        aggr(shost() "\t" $srcIpCountry, val, n+10)
#    }' "$FILE" | $TAWK -v n="$TABLE_N" '{
#        if (NR > n) printf "%%"
#        print $1 " & " $2 " & " $3 "\\\\"
#    }' > "$2" &
#}
#
#topDstIP() {
#    if [ -z "$2" ]; then
#        echo "Usage: topDstIP aggrval destfile"
#        exit 1
#    fi
#    $TAWK -v n="$TABLE_N" -v val="$1" -v '!hdr() && streq($dir, "B") && bitisset($flowStat, 1) {
#        aggr(shost() "\t" $srcIpCountry, val, n+10)
#    }' "$FILE" | $TAWK -v n="$TABLE_N" '{
#        if (NR > n) printf "%%"
#        print $1 " & " $2 " & " $3 "\\\\"
#    }' > "$2" &
#}
#
#topSrcIP "flows" "$SHOST_CN_FLOWS"
#topSrcIP "packets" "$SHOST_CN_PKTS"
#topSrcIP "bytes" "$SHOST_CN_BYTES"
#
#topDstIP "flows" "$DHOST_CN_FLOWS"
#topDstIP "packets" "$DHOST_CN_PKTS"
#topDstIP "bytes" "$DHOST_CN_BYTES"

# Source IP (flows)
$TAWK -v n="$TABLE_N" '!hdr() && streq($dir, "A") && !bitisset($flowStat,1) {
    if (srcIpCountry == 0) {
        if (privip($SrcIP4)) country = "--"
        else country = "N/A"
    } else country = $srcIpCountry
    aggr(shost() "\t" country, "flows", n+10)
}' "$FILE" | $TAWK -v n="$TABLE_N" '{
    if (NR > n) printf "%%"
    print $1 " & " $2 " & " $3 "\\\\"
}' > $SHOST_CN_FLOWS &

# Destination IP (flows)
$TAWK -v n="$TABLE_N" '!hdr() && streq($dir, "B") && bitisset($flowStat, 1) {
    if (srcIpCountry == 0) {
        if (privip($SrcIP4)) country = "--"
        else country = "N/A"
    } else country = $srcIpCountry
    aggr(shost() "\t" country, "flows", n+10)
}' "$FILE" | $TAWK -v n="$TABLE_N" '{
    if (NR > n) printf "%%"
    print $1 " & " $2 " & " $3 "\\\\"
}' > $DHOST_CN_FLOWS &

# Source IP (packets)
$TAWK -v n="$TABLE_N" '!hdr() && streq($dir, "A") && !bitisset($flowStat, 1) {
    if (srcIpCountry == 0) {
        if (privip($SrcIP4)) country = "--"
        else country = "N/A"
    } else country = $srcIpCountry
    aggr(shost() "\t" country, $numPktsSnt, n+10)
}' "$FILE" | $TAWK -v n="$TABLE_N" '{
    if (NR > n) printf "%%"
    print $1 " & " $2 " & " $3 "\\\\"
}' > $SHOST_CN_PKTS &

# Destination IP (packets)
$TAWK -v n="$TABLE_N" '!hdr() && streq($dir, "B") && bitisset($flowStat, 1) {
    if (srcIpCountry == 0) {
        if (privip($SrcIP4)) country = "--"
        else country = "N/A"
    } else country = $srcIpCountry
    aggr(shost() "\t" country, $numPktsSnt, n+10)
}' "$FILE" | $TAWK -v n="$TABLE_N" '{
    if (NR > n) printf "%%"
    print $1 " & " $2 " & " $3 "\\\\"
}' > $DHOST_CN_PKTS &

# Source IP (bytes)
$TAWK -v n="$TABLE_N" '!hdr() && streq($dir, "A") && !bitisset($flowStat, 1) {
    if (srcIpCountry == 0) {
        if (privip($SrcIP4)) country = "--"
        else country = "N/A"
    } else country = $srcIpCountry
    aggr(shost() "\t" country, $numBytesSnt, n+10)
}' "$FILE" | $TAWK -v n="$TABLE_N" '{
    if (NR > n) printf "%%"
    print $1 " & " $2 " & " $3 "\\\\"
}' > $SHOST_CN_BYTES &

# Destination IP (bytes)
$TAWK -v n="$TABLE_N" '!hdr() && streq($dir, "B") && bitisset($flowStat, 1) {
    if (srcIpCountry == 0) {
        if (privip($SrcIP4)) country = "--"
        else country = "N/A"
    } else country = $srcIpCountry
    aggr(shost() "\t" country, $numBytesSnt, n+10)
}' "$FILE" | $TAWK -v n="$TABLE_N" '{
    if (NR > n) printf "%%"
    print $1 " & " $2 " & " $3 "\\\\"
}' > $DHOST_CN_BYTES &

# Destination ports (flows)
$TAWK -v n="$CHART_N" '!hdr() && (tcp() || udp()) && streq($dir, "A") && !bitisset($flowStat, 1) {
        aggr(dport(), "flows", n)
    }' "$FILE" | $TAWK -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"]
    }' > $FLOWS_DPORT &

# Destination ports (flows)
$TAWK -v n="$CHART_N" '!hdr() && (tcp() || udp()) && streq($dir, "A") && !bitisset($flowStat, 1) {
    aggr(sport(), "flows", n)
}' "$FILE" | $TAWK -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"]
}' > $FLOWS_SPORT &

# Destination ports (packets)
$TAWK -v n="$CHART_N" '!hdr() && (tcp() || udp()) && streq($dir, "A") && !bitisset($flowStat, 1) {
    aggr(dport(), $numPktsRcvd, n)
}' "$FILE" | $TAWK -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"]
}' > $PKTS_DPORT &

# Source ports (packets)
$TAWK -v n="$CHART_N" '!hdr() && (tcp() || udp()) && streq($dir, "A") && !bitisset($flowStat, 1) {
    aggr(sport(), $numPktsSnt, n)
}' "$FILE" | $TAWK -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"]
}' > $PKTS_SPORT &

# Destination ports (bytes)
$TAWK -v n="$CHART_N" '!hdr() && (tcp() || udp()) && streq($dir, "A") && !bitisset($flowStat, 1) {
    aggr(dport(), $numBytesRcvd, n)
}' "$FILE" | $TAWK -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"]
}' > $BYTES_DPORT &

# Source ports (bytes)
$TAWK -v n="$CHART_N" '!hdr() && (tcp() || udp()) && streq($dir, "A") && !bitisset($flowStat, 1) {
    aggr(sport(), $numBytesSnt, n)
}' "$FILE" | $TAWK -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"]
}' > $BYTES_SPORT &

# Protocols
$TAWK -v n="$CHART_N" '!hdr() {
    aggr(proto(), "flows", n)
}' "$FILE" | $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
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)
}' "$FILE" | $TAWK -v n="$NAPPL" -v color="$COLOR" '
NF == 1 {
    print
    exit
}
NF > 1 {
    if (NR > n) printf "%%"
    print texscape($1) " & " $2 "\\\\"
}' > $APP_FLOWS &

# Protocols Over Non-Standard Ports
$TAWK -v n="$TABLE_N" '
BEGIN {
    if (nDPIclass == 0 || dstPortClassN == 0 || dstPortClass == 0) {
        #print "\\multicolumn{5}{c}{N/A: nDPI and portClassifier plugins required}\\\\"
        exit
    }
}
!hdr() && nonstdports() && $nDPIclass !~ /Skype/ && $nDPIclass !~ /BitTorrent/ && $nDPIclass !~ /H323/ {
    ndpiClass = gensub(/\..*/, "", 1, unquote($nDPIclass)) # master protocol only
    aggr(ndpiClass "\t" $dstPortClassN "\t" $dstPortClass, $numBytesSnt "\t" $numPktsSnt "\t" "Flows", n+10)
}' "$FILE" | $TAWK -v n="$TABLE_N" '
NF == 1 {
    exit
}
NR == 1 {
    print "\\begin{longtable}{llrrr}"
    print "{\\bf Detected} & {\\bf Expected} & {\\bf Bytes} & {\\bf Packets} & {\\bf Flows}\\\\"
    print "\\hline\\endhead"
}
{
    if (NR > n) printf "%%"
    print texscape($1) " & " texscape($3) " (" $2 ") & " $4 " & " $5 " & " $6 "\\\\"
}
END {
    if (NR >= 1) print "\\end{longtable}"
    else print "None detected"
}' > $NON_STDPORTS &

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

# DNS
$TAWK -v n="$TABLE_N" 'topDnsQ(n+10)' "$FILE" | $TAWK -v n="$TABLE_N" '
NR == 1 {
    print "\\begin{center}"
    print "%\\begin{tabularx}{\\textwidth}{Rr}"
    print "\\begin{tabular}{rr}"
    print "{\\bf DNS Query} & {\\bf Count}\\\\"
    print "\\hline"
}
{
    if (NR > n) printf "%%"
    print texscape($1) " & " $2 "\\\\"
}
END {
    if (NR < 1) print "No DNS query detected"
    else {
        print "%\\end{tabularx}"
        print "\\end{tabular}"
        print "\\end{center}"
    }
}' > $DNSQ &

$TAWK -v n="$TABLE_N" 'topDnsA(n+10)' "$FILE" | $TAWK -v n="$TABLE_N" '
NR == 1 {
    print "\\begin{center}"
    print "%\\begin{tabularx}{\\textwidth}{Rr}"
    print "\\begin{tabular}{rr}"
    print "{\\bf DNS Answer} & {\\bf Count}\\\\"
    print "\\hline"
}
{
    if (NR > n) printf "%%"
    print texscape($1) " & " $2 "\\\\"
}
END {
    if (NR < 1) print "No DNS answer detected"
    else {
        print "%\\end{tabularx}"
        print "\\end{tabular}"
        print "\\end{center}"
    }
}' > $DNSA &

$TAWK -v n="$TABLE_N" 'topDnsIp4(n+10)' "$FILE" | awk   -v n="$TABLE_N" '{ if (NR > n) printf "%%"; print          $1  " & " $2 "\\\\" }' > $DNSIP4 &
$TAWK -v n="$TABLE_N" 'topDnsIp6(n+10)' "$FILE" | awk   -v n="$TABLE_N" '{ if (NR > n) printf "%%"; print          $1  " & " $2 "\\\\" }' > $DNSIP6 &
$TAWK -v n="$TABLE_N" 'topSLD(n+10)'    "$FILE" | $TAWK -v n="$TABLE_N" '{ if (NR > n) printf "%%"; print texscape($1) " & " $2 "\\\\" }' > $SLD &
$TAWK -v n="$TABLE_N" 'topTLD(n+10)'    "$FILE" | awk   -v n="$TABLE_N" '{ if (NR > n) printf "%%"; print          $1  " & " $2 "\\\\" }' > $TLD &

# HTTP

# User-agents
$TAWK -v n="$TABLE_N" '!hdr() && $httpUsrAg {
    aggrrep($httpUsrAg, "flows", n+10)
}' "$FILE" | $TAWK -v n="$TABLE_N" '
NR == 1 {
    print "\\begin{center}"
    print "\\begin{tabularx}{\\textwidth}{Lr}"
    print "{\\bf User-Agent} & {\\bf Count}\\\\"
    print "\\hline"
}
{
    if (NR > n) printf "%%"
    print texscape($1) " & " $2 "\\\\"
}
END {
    if (NR < 1) print "No HTTP User-Agent detected"
    else {
        print "\\end{tabularx}"
        print "\\end{center}"
    }
}' > $USER_AGENTS &

# Hosts
$TAWK -v n="$TABLE_N" '!hdr() && $httpHosts {
    aggrrep($httpHosts, "flows", n)
}' "$FILE" | $TAWK -v n="$TABLE_N" '{
    if (NR > n) printf "%%"
    print texscape($1) " & " $2 "\\\\"
}' > $HTTP_HOSTS &

# Servers
$TAWK -v n="$TABLE_N" '!hdr() && $httpServ {
    aggrrep($httpServ, "flows", n)
}' "$FILE" | $TAWK -v n="$TABLE_N" '{
    if (NR > n) printf "%%"
    print texscape($1) " & " $2 "\\\\"
}' > $SERVERS &

# Content-Types
$TAWK -v n="$TABLE_N" 'topHttpMimesST(n)' "$FILE" | $TAWK -v n="$TABLE_N" '{
    if (NR > n) printf "%%"
    print texscape($1) " & " $2 "\\\\"
}' > $CONTENT_TYPES &

# Contents
$TAWK -v n="$TABLE_N" 'topHttpMimesT(n)' "$FILE" | $TAWK -v n="$TABLE_N" '{
    if (NR > n) printf "%%"
    print texscape($1) " & " $2 "\\\\"
}' > $CONTENTS &

# Status code
$TAWK '!hdr() && $httpRSCode {
    aggrrep($httpRSCode)
}' "$FILE" | $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 -v n="$TABLE_N" '!hdr() { exeDL(n+10) }' "$FILE" | $TAWK -v n="$TABLE_N" '
NR == 1 {

    print "\\begin{scriptsize}"
    print "\\begin{center}"
    print "\\begin{longtable}{llllllll}"
    print "{\\bf SrcIP4} & {\\bf DstIP4} & {\\bf Advertised Mime} & {\\bf Filename} & {\\bf Size} & {\\bf MD5}\\\\"
    print "\\hline\\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(unquote($3)) " & " texscape(fname) " & " $5 " & " $6"\\\\"
}
END {
    if (NR < 1) print "No EXE download detected"
    else {
        print "\\end{longtable}"
        print "\\end{center}"
        print "\\end{scriptsize}"
    }
}' > $EXEDL &

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

# DNS Zone Transfers
$TAWK 'dnsZT()' "$FILE" | $TAWK '
    NR == 1 {
        print "DNS Zone Transfer detected:"
        print "\\begin{longtable}{llll}"
        print "{\\bf Time} & {\\bf Client} & {\\bf Server} & {\\bf Query}\\\\"
        print "\\hline\\endhead"
    }
    {
        print $1 " & " $2 " & " $3 " & " texscape($4) "\\\\"
    }
    END {
        if (NR >= 1) print "\\end{longtable}"
        else print "No DNS zone transfer detected"
    }' > $DNSZT &

# SSH connections
$TAWK '!privip($SrcIP4) || !privip($DstIP4) { ssh() }' "$FILE" | $TAWK -v has_ssh="$($TAWK -l "$FILE" | grep sshVersion | wc -l)" '
NR == 1 {
    str = "\\begin{small}"
    str = str "\\begin{longtable}{*{7}{l}}"
    for (i = 1; i < NF; i++) {
        str = str "{\\bf " $i " } & "
    }
    str = str "{\\bf " $NF " }\\\\\n\\hline\\endhead\n"
}
NR == 2 {
    print str
}
NR > 1 {
    gsub(/\.[0-9]{6}/, "", $1) # ignore microseconds
    for (i = 1; i < NF; i++) {
        printf "%s & ", $i
    }
    printf "%s\\\\\n", texscape(unquote($NF))
}
END {
    if (NR < 2) {
        if (!has_ssh) print "N/A: ssDecode plugin required"
        else print "No SSH connection detected"
    } else {
        print "\\end{longtable}"
        print "\\end{small}"
    }
}' > $SSH &

fi # DEBUG

# Wait for all the queries to finish
wait < <(jobs -p)

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

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

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

# Fill in the placeholders
sed -i "s/__AUTHOR__/$AUTHOR/" "$OFILE"
sed -i "s/__TITLE__/$TITLE/" "$OFILE"
sed -i "s/__COLOR__/$COLOR/" "$OFILE"
sed -i "s/__FILENAME__/$(echo "$FILENAME" | $TAWK '{ print texscape($0) }' | sed 's/\\/\\\\/g')/" "$OFILE"
sed -i "s;__FULLNAME__;$(echo "$FULLNAME" | $TAWK '{ print texscape($0) }' | sed 's/\\/\\\\/g');" "$OFILE"
sed -i "s/__FILESIZE__/$FILESIZE/" "$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/__DISTIP__/$DISTINCTIP/" "$OFILE"
sed -i "s/__PRIVIP__/$DISTINCTPRIVIP/" "$OFILE"
sed -i "s/__PUBIP__/$DISTINCTPUBIP/" "$OFILE"
sed -i "s/__TABLE_N__/$TABLE_N/g" "$OFILE"
sed -i "s/__CHART_N__/$CHART_N/g" "$OFILE"
sed -i "s/__MD5SUM__/$(cat $MD5SUM)/" "$OFILE"
sed -i "s/__NUMPKTS__/$(cat $NUMPKTS)/" "$OFILE"
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"
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"
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
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"
# HTTP
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"
# Warnings
sed -i "/__HTTP_EXE_DL__/r$EXEDL" "$OFILE"
sed -i "/__ARP_SPOOF__/r$ARPSPOOF" "$OFILE"
sed -i "/__DNS_ZT__/r$DNSZT" "$OFILE"
sed -i "/__SSH_CONN__/r$SSH" "$OFILE"

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

cd "$ODIR"
pdflatex -halt-on-error -interaction=nonstopmode "$OFILE" > /dev/null && pdflatex "$OFILE" &> /dev/null && pdflatex "$OFILE" > /dev/null
ret="$?"
cd "$OLDPWD"

PDFFILE="$(sed 's/\.tex/.pdf/' <<< "$OFILE")"

if [ $ret -eq 0 ]; then
    _printok "Successfully generated '$PDFFILE'" #in X seconds.
    exit 0
else
    _printerr "Failed to generate '$PDFFILE'"
    exit 1
fi
