#!/usr/bin/env bash
#
# TODO
#   - check for duplicate column names?
#   - pass options to tshark: -T fields -e ...?

source "$(dirname "$0")/../t2utils.sh"

if [ -n "$DISPLAY" ] || [ "$(uname)" = "Darwin" ]; then
    HAS_GUI=1
fi

usage() {
    printf "Usage:\n"
    printf "    $SNAME [OPTION...] 'program' file_flows.txt\n"
    printf "    $SNAME [OPTION...] -I file_flows.txt 'program'\n"
    printf "\n"
    printf "Input arguments:\n"
    printf "    -I file             Alternative way to specify the input file\n"
    printf "\n"
    printf "Optional arguments:\n"
    printf "    -N num              Row number where column names are to be found\n"
    printf "    -s char             First character for the row listing the columns name\n"
    printf "    -F fs               Use 'fs' as input field separator\n"
    printf "    -O fs               Use 'fs' as output field separator\n"
    printf "    --csv               Set input and output separators to ',' and\n"
    printf "                        extract names from first row\n"
    printf "    --zeek              Configure tawk to work with Bro/Zeek log files\n"
    printf "    -n                  Load nfdump functions\n"
    printf "    -e                  Load examples functions\n"
    printf "    -X xerfile          Specify the '.xer' file to use with -k and -x options\n"
    printf "    -x outfile          Run the fextractor on the extracted data\n"
    printf "    -P                  Extract specific packets instead of whole flows\n"
    if [ "$HAS_GUI" ]; then
        printf "    -k                  Run Wireshark on the extracted data\n"
    fi
    printf "    -t                  Do not validate column names\n"
    printf "    -r                  Try renaming invalid columns (suffix them with '_')\n"
    printf "    -H                  Do not output the header (column names)\n"
    printf "    -c[=u]              Output command line as a comment\n"
    printf "                        (use -c=u for UTC instead of localtime)\n"
    printf "\n"
    printf "Help and documentation arguments:\n"
    printf "    -l[=n], --list[=n]  List column names and numbers\n"
    printf "    -g[=n], --func[=n]  List available functions\n"
    printf "\n"
    printf "    -d fname            Display function 'fname' documentation\n"
    printf "    -V vname[=value]    Display variable 'vname' documentation\n"
    printf "\n"
    printf "    -L                  Decode all variables from Tranalyzer log file\n"
    printf "\n"
    if [ "$HAS_GUI" ]; then
        printf "    -D                  Display tawk PDF documentation\n"
        printf "\n"
    fi
    printf "    -?, -h, --help      Show help options and exit\n"
}

_printwrn() {
    printf "${ORANGE}${1}${NOCOLOR}\n" >&2  # Orange
}

# $1: name of the option
_abort_no_x_server() {
    printerr "Option '$1' requires a running X server"
    exit 1
}

_get_wireshark() {
    local wshark
    if [ ! "$HAS_GUI" ]; then
        wshark="tshark"  # TODO package name?!
    else
        wshark="wireshark"
        for i in "$wshark" "wireshark-qt" "wireshark-gtk" "tshark"; do
            if type "$i" &> /dev/null; then
                wshark="$i"
                break
            fi
        done
    fi
    echo "$wshark"
}

_setup_wireshark() {
    local wshark="$(_get_wireshark)"
    check_dependency "$wshark"
    WIRESHARK="$(which "$wshark")"
    if [ "$wshark" = "tshark" ]; then
        WSHARK_OPTS=(-r -)
    else
        WSHARK_OPTS=(-k -i -)
    fi
}

_setup_fextractor() {
    FEXTRACTOR="$(find_most_recent_file "$T2PLHOME/findexer" "fextractor")"
    if [ ! -f "$FEXTRACTOR" ]; then
        printerr "fextractor not found"
        exit 1
    fi
    FEX_OPTS+=(-b -f -i -)
    PRIHDR=0
}

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

    local ret=$1

    #printinf "Cleaning temporary files"
    rm -f "$TEMPFILE"

    exit $ret
}

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

list_names() {
    local cnt=1
    local d="${1:-1}"
    local table=$(
        for i in ${names[@]}; do
            printf "%3d\t%s" $cnt $i
            if [ $((d > 1 ? cnt%d : 0)) -eq 0 ]; then
                printf "\n"
            else
                printf "\t"
            fi
            cnt=$((cnt+1))
        done)
    printf "%s\n" "$table" | column -t -s $'\t'
}

list_funcs() {
    local cnt=1
    local d="${1:-1}"
    local dir=("$TAWKHOME/funcs/")
    dir+=("$TAWKHOME/t2custom/")
    [ $NFDUMP ] && dir+=("$TAWKHOME/t2nfdump/")
    [ $EXAMPLES ] && dir+=("$TAWKHOME/examples/")
    local funcs=($(find "${dir[@]}" -maxdepth 1 -type f ! -name '*.load' ! -name '.*'))
    if [ -z "$funcs" ]; then
        printerr "No functions available"
        exit 1
    fi
    local table=$(
        for i in ${funcs[@]}; do
            i="$(AWK -F'/' '{ print $NF }' <<< "$i")"
            printf "%s" $i
            if [ $((d > 1 ? cnt%d : 0)) -eq 0 ]; then
                printf "\n"
            else
                printf "\t"
            fi
            cnt=$((cnt+1))
        done | sort)
    printf "%s\n" "$table" | column -t -s $'\t'
}

validate_names() {
    local array=()

    # Extract all variable names from 'program'
    for i in $ARGS; do
        while [ -n "$(grep "\$[a-zA-Z0-9_]\+" <<< "$i")" ]; do
            local n="$($SED 's/.*\$\([a-zA-Z0-9_]\+\).*/\1/' <<< "$i")"
            i="$($SED 's/\(.*\)\$[a-zA-Z0-9_]\+\(.*\)/\1\2/' <<< "$i")"
            if [ -z "$($SED 's/^[0-9]\+$//' <<< "$n")" ] || [ "$n" = "NF" ]; then
                # do not validate $0,$1,..., $NF
                continue
            else
                array+=($n)
            fi
        done
    done

    local start=${#array[@]}
    local stop
    if [ -n "$ZSH_VERSION" ]; then
        # zsh arrays start at 1... d'oh!
        stop=1
    else
        start=$((start-1))
        stop=0
    fi

    # Make sure all variables exist
    for ((i = $start; i >= $stop; i--)); do
        for j in ${names[@]}; do
            if [ "${array[i]}" = "$j" ]; then
                if [ -n "$ZSH_VERSION" ]; then
                    array[$i]=()
                else
                    unset array[$i]
                fi
                break
            fi
        done
    done

    if [ ${#array[@]} -ne 0 ]; then
        for i in ${array[@]}; do
            printerr "Column '$i' not found"
            for j in ${names[@]}; do
                if [ "$(fgrep -i "$i" <<< "$j")" ]; then
                    printinf "Did you mean '$j'?"
                fi
            done
        done
        exit 1
    fi
}

funcdoc() {
    local fname="$1"
    # Extract the function name and parameters excluding the local variables (separated from the parameters by 8 spaces)
    local func="$($SED -n "s/^function\s\+\($fname(.*\)).*/\1/p" "$TAWKHOME/"*"/$fname" | AWK -F"        " '{ gsub(",$", "", $1); print $1 ")" }')"
    if [ -z "$func" ]; then
        func="$fname"
    fi
    printf "${ORANGE_BOLD}${func}:${NOCOLOR}\n\n"
    AWK '
        /^[^#]/ { exit }
        NR > 2 { gsub(/^#/, " "); print }
    ' "$TAWKHOME/"*"/$fname"
}

doc() {
    local fnames="$1"
    if [ "$1" = "all" ] || [ "$fnames" = "funcs" ]; then
        fnames="$(ls "$TAWKHOME/funcs/"* | AWK -F'/' '{print $NF}' | grep -v funcs.load | xargs | tr ' ' ',')"
    fi
    if [ "$1" = "all" -a "$EXAMPLES" ] || [ "$fnames" = "examples" ]; then
        fnames="$fnames,$(ls "$TAWKHOME/examples/"* | AWK -F'/' '{print $NF}' | grep -v examples.load | xargs | tr ' ' ',')"
    fi
    if [ "$1" = "all" -a "$NFDUMP" ] || [ "$fnames" = "t2nfdump" ]; then
        fnames="$fnames,$(ls "$TAWKHOME/t2nfdump/"* | AWK -F'/' '{print $NF}' | grep -v t2nfdump.load | xargs | tr ' ' ',')"
    fi
    for i in $(tr ',' ' ' <<< "$fnames"); do
        if [ "$i" = "examples" ] || [ "$i" = "t2nfdump" ]; then
            continue
        fi
        if [ -f "$TAWKHOME/examples/$i" ] ||
           [ -f "$TAWKHOME/funcs/$i" ]    ||
           [ -f "$TAWKHOME/t2nfdump/$i" ]
        then
            funcdoc "$i"
        else
            printerr "No documentation available for function '$i'"
        fi
    done
}

vardoc() {
    local vname="$1"
    local name="$(cut -d= -f1 <<< "$vname")"
    local val="$(cut -s -d= -f2 <<< "$vname")"
    if [ ! -f "$TAWKHOME/vars/$name" ]; then
        printerr "No documentation available for variable '$name'"
        exit 1
    fi
    # variable name in bold and orange
    printf "\nThe ${ORANGE_BOLD}${name}${NOCOLOR} column "
    if [ -n "$val" ]; then
        printf "with value ${BOLD}${val}${NOCOLOR} "
    fi
    printf "is to be interpreted as follows:\n\n"
    local awk_opts=(
        -v OFS='|'
        -F'|'
        -v val="$val"
        -i "$TAWKHOME/funcs/strip"
    )
    if _awk_has_bignum; then
        awk_opts+=(-M -v PREC=256)
    fi
    AWK ${awk_opts[*]} '
        function isnum(v) { return (v == v + 0 || v ~ /0x[0-9a-fA-F]+/) }
        BEGIN {
            nval = split(val, _aval, /_/)
            vval = isnum(val) ? strtonum(val) : val
        }
        /^#H/   { COLOR = "\033[1m"    } # Header, bold
        /^#I/   { COLOR = "\033[0;34m" } # Info, blue
        /^#W/   { COLOR = "\033[0;33m" } # Warning, orange
        /^#E/   { COLOR = "\033[0;31m" } # Error, red
        /^[^#]/ { COLOR = "\033[0m"    } # Default
        {
            gsub(/^#./, "  ")
            # Print headers and all the rows if no value specified
            pri = (NR < 3 || !length(val))
            if (!pri) {
                # Only two columns: value and description
                if (NF == 2 || (NF == 3 && $2 !~ /0[xX][a-fA-F0-9]+/)) {
                    _val = strip($1)
                    if (_val ~ /^0x[0-9a-fA-F]+-0x[0-9a-fA-F]+/ || _val ~ /^[0-9]+-[0-9]+/) {
                        split(_val, _v, /-/)
                        if (_v[1] ~ /^0x/) _v[1] = strtonum(_v[1])
                        if (_v[2] ~ /^0x/) _v[2] = strtonum(_v[2])
                        pri = (_v[1] <= vval && vval <= _v[2])
                    } else {
                        if (_val ~ /^0x/) _val = strtonum(_val)
                        pri = (_val == vval)
                    }
                # Five columns: bit, hex value, bit, hex value and description
                } else if (NF == 5) {
                    tmp2 = gensub(/\s+/, "", "g", $2)
                    if (length(tmp2) == 0) {
                        tmp2 = last_tmp2
                    }
                    hex = strtonum(tmp2)
                    last_tmp2 = hex
                    pri = and(hex, strtonum(_aval[1]))
                    tmp4 = gensub(/\s+/, "", "g", $4)
                    if (pri && nval == 2 && length(tmp4) > 0) {
                        hex = strtonum(tmp4)
                        pri = and(hex, strtonum(_aval[2]))
                    }
                # Three columns: bit, hex value and description
                } else {
                    hex = strtonum(gensub(/\s+/, "", "g", $2))
                    if ($2 && vval == 0 && hex == 0) {
                        pri = 1
                    } else {
                        pri = and(hex, vval)
                    }
                }
            }
            if (pri) {
                printf "%s%s\033[0m\n", COLOR, $0
            }
        }
        END {
            printf "\n"
        }
    ' "$TAWKHOME/vars/$name"
}

# Default values
HDRSEP="%" # First character for the row listing the columns name
FS=$'\t'   # Field Separator
OFS=$'\t'  # Output Field Separator
PRIHDR=1   # Keep the column names
VALIDATE_NAMES=1
FEX_OPTS=()
XER_SUFFIX="_flows"

while [ $# -gt 0 ]; do
    case "$1" in
        -F|--field-separator)
            validate_next_arg "$1" "$2"
            FS="$2"
            shift
            ;;
        -F*)
            FS="${1#*F}"
            ;;
        -O|--output-field-separator|--ofs)
            validate_next_arg "$1" "$2"
            OFS="$2"
            shift
            ;;
        -O=*|--ofs=*|--output-field-separator=*)
            OFS="${1#*=}"
            ;;
        -O*)
            OFS="${1#*O}"
            ;;
        -N[0-9]*)
            HDRROW="${1#*N}"
            ;;
        -N=*|--header-row=*)
            HDRROW="${1#*=}"
            if [ -n "$(tr -d '0-9' <<< "$HDRROW")" ]; then
                printerr "Option '${1%=*}' requires a numeric argument"
                abort_with_help
            fi
            ;;
        -N|--header-row)
            validate_next_arg "$1" "$2"
            if [ -n "$(tr -d '0-9' <<< "$2")" ]; then
                printerr "Option '$1' requires a numeric argument"
                abort_with_help
            fi
            HDRROW="$2"
            shift
            ;;
        -s|--special-header)
            # Comment out the following line to force the row with
            # the column names to start with a special character
            #validate_next_arg "$1" "$2"
            HDRSEP="$2"
            shift
            ;;
        -s*)
            HDRSEP="${1#*s}"
            ;;
        -c|-c=*|--comment=*|--comment)
            COMMENT=1
            if [ "${1#*=}" = "u" ]; then
                UTC="-u"
            fi
            ;;
        --csv)
            FS=","
            OFS=","
            HDRROW=1
            unset HDRSEP
            ;;
        --bro|--zeek)
            ZEEK=1
            FIX_NAMES=1
            HDRSEP="#fields"
            ;;
        -H|--no-header) PRIHDR=0;;
        -r|--rename) FIX_NAMES=1;;
        -t|--no-names-validation) unset VALIDATE_NAMES;;
        -e|--examples) EXAMPLES=1;;
        -n|--nfdump) NFDUMP=1;;
        -l|--list) LIST_NAMES=1;;
        -l=*|--list=*)
            LIST_NAMES="${1#*=}"
            if [ -z "$LIST_NAMES" ] || [ -n "$(tr -d '0-9' <<< "$LIST_NAMES")" ]; then
                printerr "Option '${1%=*}' requires a numeric argument"
                abort_with_help
            fi
            ;;
        -g|--func) LIST_FUNCS=1;;
        -g=*|--func=*)
            LIST_FUNCS="${1#*=}"
            if [ -n "$(tr -d '0-9' <<< "$LIST_FUNCS")" ]; then
                printerr "Option '${1%=*}' requires a numeric argument"
                abort_with_help
            fi
            ;;
        -k|--wireshark)
            _setup_wireshark
            _setup_fextractor
            ;;
        -X|--xer-file)
            validate_next_file "$1" "$2"
            XER_FILE="$2"
            shift
            ;;
        -x|--fextractor)
            validate_next_arg "$1" "$2"
            _setup_fextractor
            OUT_FILE="$2"
            shift
            ;;
        -P|--packets)
            FEX_OPTS+=(-P)
            XER_SUFFIX="_packets"
            ;;
        -d|--doc)
            validate_next_arg "$1" "$2"
            DOC+=("$2")
            shift
            ;;
        -V|--var)
            validate_next_arg "$1" "$2"
            VDOC+=("$2")
            shift
            ;;
        -L|--decode-log)
            DECODE_LOG=1
            ;;
        -I|--input)
            validate_next_file "$1" "$2"
            FILE+=("$2")
            IOPTION=1
            shift
            ;;
        -D|--pdf)
            [ ! "$HAS_GUI" ] && _abort_no_x_server "$1"
            if [ ! -f "$TAWKHOME/doc/tawk.pdf" ]; then
                if ! hash make 2> /dev/null; then
                    printerr "tawk.pdf not found in $TAWKHOME/doc/"
                    exit 1
                fi
                make -C "$TAWKHOME/doc" || {
                    printerr "Failed to build documentation for 'tawk'"
                    exit 1
                }
            fi
            "$OPEN" "$TAWKHOME/doc/tawk.pdf"
            exit 0
            ;;
        -\?|-h|--help)
            usage
            exit 0
            ;;
        # awk options with file as arguments
        -i|--include|-f|--file)
            ARGS+=("$1")
            if [ -f "$2" ]; then
                ARGS+=("$2")
                shift
            fi
            ;;
        *)
            if [ -f "$1" ] && [ -z "$FILE" ] && [ $# -eq 1 ]; then
                FILE="$1"
            else
                ARGS+=("$1")
            fi
            ;;
    esac
    shift
done

if [ -n "$OUT_FILE" ] && [ -n "$WIRESHARK" ]; then
    printerr "Cannot use '-k' and '-x' options simultaneously"
    abort_with_help
fi

if [ -n "$DOC" ]; then
    for i in "${DOC[@]}"; do
        doc "$i"
    done
    exit 0
fi

if [ $LIST_FUNCS ]; then
    list_funcs "$LIST_FUNCS"
    exit 0
fi

# Gawk >= 4.2 is required for tawk (gawk -i and -M options)
_check_awk_version

if [ -n "$VDOC" ]; then
    for i in "${VDOC[@]}"; do
        vardoc "$i"
    done
    exit 0
fi

if [ -t 0 ] && [ -p /dev/stdin ]; then
    if [ -z "$FILE" ]; then
        printerr "Input file is required"
        abort_with_help
    elif [ ! -f "$FILE" ]; then
        printerr "$FILE does not exist or is not a regular file"
        abort_with_help
    fi
fi

if [ -n "$DECODE_LOG" ]; then
    AWK '{
        for (i = 1; i <= NF; i++) {
            if ($i ~ /[^=]=[^=]/) {
                gsub(/,$/, "", $i)
                print "-V " $i
            }
        }
    }' "$FILE" | xargs "$TAWK"
    exit 0
fi

if [ -f "$FILE" ]; then
    set -o pipefail
    names=($(AWK -i $TAWKHOME/funcs/hdr \
                 -i $TAWKHOME/funcs/printerr \
                 -i $TAWKHOME/funcs/strip \
                 -v __HDRROW__="$HDRROW" \
                 -v __HDRSEP__="$HDRSEP" \
                 -F"$FS" -v OFS=$'\t' '
        hdr() {
            # Remove leading __HDRSEP__
            gsub("^" __HDRSEP__ "\\s*", "", $0)
            _n = split($0, _name, FS)
            for (_i = 1; _i <= _n; _i++) {
                _name[_i] = strip(_name[_i])
                if (length(_name[_i]) == 0) {
                    printerr("Column " i " has an empty name")
                    exit 1
                }
                print _name[_i]
            }
            exit
        }' "$FILE" | tr ' (){}[] -./' '_'))
    set +o pipefail
    ret=${PIPESTATUS[0]}
    if [ $ret -ne 0 -o -z "$names" ] && { [ $LIST_NAMES ] || [ $VALIDATE_NAMES ]; }; then
        [ $ret -eq 0 ] && printerr "Column names not found"
        if [ ! $LIST_NAMES ]; then
            printinf "Use '-t' option to ignore this error"
        fi
        exit 1
    fi

    if [ $VALIDATE_NAMES ]; then
        # FIXME Check that no column name matches a function name (slow)
        FUNCS="$(list_funcs | AWK 'NR > 1 { printf "," } { printf "\"" $0 "\"" }
            END {
                # builtin/reserved awk names
                printf ", \"break\"" \
                       ", \"continue\"" \
                       ", \"delete\"" \
                       ", \"do\"" \
                       ", \"else\"" \
                       ", \"exit\"" \
                       ", \"for\"" \
                       ", \"getline\"" \
                       ", \"gsub\"" \
                       ", \"gensub\"" \
                       ", \"index\"" \
                       ", \"in\"" \
                       ", \"int\"" \
                       ", \"if\"" \
                       ", \"length\"" \
                       ", \"match\"" \
                       ", \"next\"" \
                       ", \"nextfile\"" \
                       ", \"print\"" \
                       ", \"printf\"" \
                       ", \"rand\"" \
                       ", \"return\"" \
                       ", \"split\"" \
                       ", \"sprintf\"" \
                       ", \"srand\"" \
                       ", \"sub\"" \
                       ", \"substr\"" \
                       ", \"system\"" \
                       ", \"switch\"" \
                       ", \"tolower\"" \
                       ", \"toupper\"" \
                       ", \"while\""
            }')"
        NAMES="$(echo "${names[*]}" | $SED 's/\s\+/","/g; s/^/"/; s/$/"/')"
        PYTHON="$(which python3 python python2 2> /dev/null | head -1)"
        if [ -z "$PYTHON" ]; then
            printerr "None of python3, python or python2 could be found"
            exit 1
        fi
        INVALID="$("$PYTHON" <<< "print({$NAMES}.intersection({$FUNCS}))" | $SED -r 's/^set\(\[?//; s/\]?\)$//')"
        if [ -n "$INVALID" ]; then
            if [ ! "$FIX_NAMES" ]; then
                printerr "The following column names clash with gawk/tawk builtins: $INVALID"
                printinf "Try renaming them differently or use 'tawk -r' option"
                exit 1
            else
                for i in ${!names[@]}; do
                    REDEFINED="$(grep -w -F "${names[$i]}" <<< "$INVALID")"
                    if [ -n "$REDEFINED" ]; then
                        #printerr "A function named '${names[$i]}' already exists."
                        # Append an underscore to avoid name collision
                        names[$i]+="_"
                    fi
                done
            fi
        fi
    fi

    if [ $LIST_NAMES ]; then
        list_names "$LIST_NAMES"
        exit 0
    fi

    if [ $VALIDATE_NAMES ]; then
        validate_names
    fi

    if [ -n "$FEXTRACTOR$WIRESHARK" ] && [ -z "$XER_FILE" ]; then
        XER_FILE="$(AWK -F. -v OFS=. -v XER_SUFFIX="$XER_SUFFIX" 'NF > 1 {
            # _packets.txt -> _flows.xer
            gsub(/_packets$/, XER_SUFFIX, $(NF-1))
            # _packets_cc.txt -> _flows.xer
            # _flows_dns.txt  -> _flows.xer
            gsub(/_(flows|packets)_[^_]+$/, XER_SUFFIX, $(NF-1))
            # Keep trailing numbers (-W option)
            match($NF, /([0-9]+)$/, idx)
            $NF = "xer" idx[1]
        } { print }' <<< "$FILE")"
        if [ ! -f "$XER_FILE" ]; then
            printerr "Could not find '$XER_FILE'"
            exit 1
        fi
    fi
fi

if [ -f "$FILE" ] && [ -n "$IOPTION" ] && [ ! -t 0 ]; then
    # Reading from stdin
    unset FILE
fi

if [ -z "$ARGS" ]; then
    if [ $LIST_NAMES ]; then
        printerr "Input file is required"
    else
        printerr "Program is required"
    fi
    abort_with_help
fi

# Default gawk options
OPTS=()

if _awk_has_bignum; then
    OPTS+=(-M -v PREC=256)
fi

OPTS+=(
    -v __PRIHDR__=$PRIHDR
    -v __UNAME__="$(uname)"
    -v __HDRROW__="$HDRROW"
    -v __TAWKHOME__="$SHOME"
)

trap "trap - SIGTERM && _cleanup 1" HUP INT QUIT TERM
trap "_cleanup \$?" EXIT

# Prepare mapping between columns name and number
TEMPFILE=`(tempfile) 2> /dev/null` || TEMPFILE=/tmp/tawk$$
echo "BEGIN {" > "$TEMPFILE"
CNT=1
for i in ${names[@]}; do
    echo "$i = $CNT" >> "$TEMPFILE"
    echo "COL[\"$i\"] = $CNT" >> "$TEMPFILE"
    echo "COL[$CNT] = \"$i\"" >> "$TEMPFILE"
    CNT=$((CNT+1))
done
echo "}" >> "$TEMPFILE"

# Load mapping column names/numbers
OPTS+=(-i "$TEMPFILE")

if [ $ZEEK ]; then
    OPTS+=(-v __ZEEK__=1 -i "$TAWKHOME/zeek/vars" -i "$TAWKHOME/zeek/skip_comments")
fi

# Load tawk functions
AWKPATH="$TAWKHOME/funcs/"
OPTS+=(-i "$TAWKHOME/funcs/funcs.load")

if [ $NFDUMP ]; then
    AWKPATH="${AWKPATH}:$TAWKHOME/t2nfdump/"
    OPTS+=(-i "$TAWKHOME/t2nfdump/t2nfdump.load");
fi

if [ $EXAMPLES ]; then
    AWKPATH="${AWKPATH}:$TAWKHOME/examples/"
    OPTS+=(-i "$TAWKHOME/examples/examples.load");
fi

if [ -f "$TAWKHOME/t2custom.load" ] && [ -n "$(AWK '/^@include/' "$TAWKHOME/t2custom.load")" ]; then
    AWKPATH="${AWKPATH}:$TAWKHOME/t2custom/"
    OPTS+=(-i "$TAWKHOME/t2custom/t2custom.load")
fi

if [ $COMMENT ]; then
    printf "# Generated with $SNAME from '${FILE:-stdin}'\n"
    printf "# Date: $(date $UTC +"%FT%T%z")"
    if [ "$(fgrep -e '-v ' -e '-i ' <<< "${ARGS[*]}")" ]; then
        printf "\n# Variables and libraries used:"
        for i in ${ARGS[*]}; do
            if [[ $i = '-i' ]] || [[ $i = '-v' ]]; then
                _v=1
                printf " %s" "$i"
            elif [ "$_v" ]; then
                printf " %s" "$i"
                unset _v
            fi
        done
    fi
    printf "\n# Filter used:"
    for i in ${ARGS[*]}; do
        if [[ "$i" = '-i' ]] || [[ "$i" = '-v' ]]; then
            _v=1
        elif [ "$_v" ]; then
            unset _v
        else
            printf " %s" "$i"
        fi
    done
    printf "\n"
fi

export AWKPATH

if [ -z "$FEXTRACTOR$WIRESHARK" ]; then
    AWK ${OPTS[*]} -F"$FS" -v OFS="$OFS" -v __HDRSEP__="$HDRSEP" "${ARGS[@]}" "${FILE[@]}"
elif [ ! -f "$FILE" ]; then
    printerr "Input file is required"
    abort_with_help
elif [ -z "$WIRESHARK" ]; then
    AWK ${OPTS[*]} -F"$FS" -v OFS="$OFS" -v __HDRSEP__="$HDRSEP" "${ARGS[@]}" "${FILE[@]}" | \
        "$FEXTRACTOR" ${FEX_OPTS[*]} -r "$XER_FILE" -w "$OUT_FILE"
else
    AWK ${OPTS[*]} -F"$FS" -v OFS="$OFS" -v __HDRSEP__="$HDRSEP" "${ARGS[@]}" "${FILE[@]}" | \
        "$FEXTRACTOR" ${FEX_OPTS[*]} -r "$XER_FILE" -w - | \
        $WIRESHARK ${WSHARK_OPTS[*]}
fi
