#!/bin/bash
#
# Produces a timeline plot of a flow file using the timestamps and the findex

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

usage() {
    echo "Usage:"
    echo "    $SNAME [OPTION...] <FILE_flows.txt>"
    echo
    echo "Optional arguments:"
    echo "    -r            Use relative time, i.e., start at 0"
    echo "    -e fields     Extra fields to display in the tooltip, e.g., -e macS,macD"
    echo "    -v vspace     Vertical space to add between A and B flows"
    echo "    -h, --help    Show this help, then exit"
}

while [ $# -ne 0 ]; do
    case "$1" in
        -r) RELATIVE=1;;
        -e)
            validate_next_arg "$1" "$2"
            EXTRA="$2"
            shift
            ;;
        -v)
            validate_next_num "$1" "$2"
            VSPACE="$2"
            shift
            ;;
        -h|-\?|--help) usage; exit 0;;
        *)
            if [ ! -f "$1" ]; then
                abort_option_unknown "$1"
            fi
            FLOWFILE="$1"
            ;;
    esac
    shift
done

if [ ! -f "$FLOWFILE" ]; then
    abort_required_file
fi

PREFIX="$($AWK -F. 'NF > 1 { NF-- } { print; exit }' <<< "$FLOWFILE")"

$TAWK -v prefix="$PREFIX" -v extra="$EXTRA" -v vspace="$VSPACE" -v reltime="$RELATIVE" '
!hdr() {
    a = $flowInd "_" $flowStat "_" $srcIP4 ":" $srcPort "_" $dstIP4 ":" $dstPort "_" proto() "_" $ethVlanID
    if (length(extra) > 0) {
        n = split(extra, x, /,/)
        for (i = 1; i <= n; i++) {
            _validate_col(COL[x[i]], x[i])
            a = a "_" $COL[x[i]]
        }
    }

    if (!firstTime && reltime) firstTime = timestamp($timeFirst)

    if (bitisset($flowStat, 0x1)) {
        printf "%f\t%f\t%s\t%d\t%s\n", timestamp($timeFirst) - firstTime, $flowInd - vspace, $duration, 0, a > prefix"_b.txt"
    } else {
        printf "%f\t%f\t%s\t%d\t%s\n", timestamp($timeFirst) - firstTime, $flowInd, $duration, 0, a > prefix"_a.txt"
    }
}' "$FLOWFILE"

if [ $? -ne 0 ]; then
    # One of the column could not be found
    exit
fi

# build the gnuplot command
GPCMD+=("set term qt size 2000,1200 dashed title \"Tranline\";")
GPCMD+=("set title \"Anteaters Timeline\" font \"Times-Bold,20\";")
GPCMD+=("set xlabel \"Time [s.us]\" offset -15 font \"Times-Bold,20\";")
GPCMD+=("set ylabel \"Flow Number\" offset -5 font \"Times-Bold,20\";")
GPCMD+=("plot \"${PREFIX}_a.txt\" u 1:2:3:4 w vectors heads size screen 0.002,90 ls 2,")
GPCMD+=("     \"${PREFIX}_a.txt\" u 1:2:5 w labels hypertext point pt 0,")
GPCMD+=("     \"${PREFIX}_b.txt\" u 1:2:3:4 w vectors heads size screen 0.002,90 ls 7,")
GPCMD+=("     \"${PREFIX}_b.txt\" u 1:2:5 w labels hypertext point pt 0;")
GPCMD+=("pause 1000;")
GPCMD+=("exit")

echo ${GPCMD[*]} | gnuplot -p
