#!/usr/bin/env bash
#
# This script transform packet signal from nFrstPkts in flow file to
# gnuplot or t2plot format.
# It depends on the configuration of the nFrstPkts plugin.
# The '-j' option can be used to calculate the jumps in IAT to allow the user
# to choose an appropriate MINIAT(S/U)

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

usage() {
    echo "Usage:"
    echo "    $SNAME [OPTION...] <FILE_flows.txt>"
    echo
    echo "Optional arguments:"
    echo "    -f findex        Flow index to extract [default: all flows]"
    echo "    -d A|B           Flow direction: A or B only [default: A and B]"
    echo
    echo "    -s               Time sorted ascending"
    echo "    -t               No time, but counts on x axis [default: time on x axis]"
    echo "    -i               Invert B flow PL"
    echo "    -p s             Sample sorted signal with smplIAT in [s]; f = 1/smplIAT"
    echo "    -e s             Time for each PL pulse edge in [s]"
    echo
    echo "    -j               Calculate the jumps in IAT and report appropriate values"
    echo "                     for MINIAT(S/U)"
    echo
    echo "    -P               Plot the packet signal"
    echo
    echo "    --gif  file      Generate a GIF file"
    echo "    --jpeg file      Generate a JPEG file"
    echo "    --png  file      Generate a PNG file"
    echo "    --svg  file      Generate a SVG file"
    echo
    echo "t2plot arguments:"
    echo "    $SNAME supports t2plot options."
    echo "    Run t2plot --help for more information."
    echo
    echo "Help and documentation arguments:"
    echo "    -h, --help       Show this help, then exit"
}

# Default config values

# Time for each PL pulse edge between 0 and PL in s
EDG=0.000010

# x-axis is time
TM=1

# do not invert B flow PL
INVB=0

T2PLOT_OPTS=()
while [ $# -ne 0 ]; do
    case "$1" in
        -f|--flowInd)
            validate_next_num "$1" "$2"
            FLI="$2"
            shift
            ;;
        -d|--dir)
            validate_next_arg "$1" "$2"
            if [ -n "$(tr -d 'AB' <<< "$2")" ]; then
                printerr "Invalid argument for option '$1': expected 'A' or 'B'; found '$2'"
                abort_with_help
            fi
            case "$2" in
                A) DIR=0;;
                B) DIR=1;;
                AB) ;;
            esac
            shift
            ;;
        -p|--sample)
            validate_next_arg "$1" "$2"
            smplIAT="$2"
            shift
            ;;
        -e|--edge)
            validate_next_arg "$1" "$2"
            EDG="$2"
            shift
            ;;
        -t|--time) TM=0;;
        -i|--invB) INVB=1;;
        -s|--sort) SRT=1;;
        -j) JMP=1;;
        -P|--plot) PLOT=1;;
        --gif|--jpeg|--png|--svg)
            validate_next_arg "$1" "$2"
            T2PLOT_OPTS+=("$1" "$2")
            shift
            ;;

        # t2plot options
        -s|--subtitle|-t|--title)
            validate_next_arg "$1" "$2"
            T2PLOT_OPTS+=("$1" "$2")
            shift
            ;;
        --no-title)
            T2PLOT_OPTS+=("$1")
            ;;
        -sx|--xrange)
            validate_next_arg_exists "$1" "$2"
            if [ -n "$(perl -pe 's/^(?:-?[0-9]+(?:.[0-9]*)?|\*):(?:-?[0-9]+(?:.[0-9]*)?|\*)$//' <<< "$2")" ]; then
                printerr "Invalid argument for option '$1': expected begin:end; found '$2'"
                abort_with_help
            fi
            T2PLOT_OPTS+=("$1" "$2")
            shift
            ;;
        -sy|--yrange)
            validate_next_arg_exists "$1" "$2"
            if [ -n "$(perl -pe 's/^(?:-?[0-9]+(?:.[0-9]*)?|\*):(?:-?[0-9]+(?:.[0-9]*)?|\*)$//' <<< "$2")" ]; then
                printerr "Invalid argument for option '$1': expected begin:end; found '$2'"
                abort_with_help
            fi
            T2PLOT_OPTS+=("$1" "$2")
            shift
            ;;
        -sz|--zrange)
            validate_next_arg_exists "$1" "$2"
            if [ -n "$(perl -pe 's/^(?:-?[0-9]+(?:.[0-9]*)?|\*):(?:-?[0-9]+(?:.[0-9]*)?|\*)$//' <<< "$2")" ]; then
                printerr "Invalid argument for option '$1': expected begin:end; found '$2'"
                abort_with_help
            fi
            T2PLOT_OPTS+=("$1" "$2")
            shift
            ;;
        -v|--rotate)
            validate_next_arg "$1" "$2"
            if [ -n "$(perl -pe 's/^[0-9]+(.[0-9]*)?,[0-9]+(.[0-9]*)?$//' <<< "$2")" ]; then
                printerr "Invalid argument for option '$1': expected rotx,rotz; found '$2'"
                abort_with_help
            fi
            T2PLOT_OPTS+=("$1" "$2")
            shift
            ;;
        -rx|--rotate-x-labels|-ry|--rotate-y-labels)
            validate_next_int "$1" "$2"
            T2PLOT_OPTS+=("$1" "$2")
            shift
            ;;
        -ts|--tsize|--t-size|--title-size)
            validate_next_num "$1" "$2"
            T2PLOT_OPTS+=("$1" "$2")
            shift
            ;;
        -ls|--lsize|--l-size|--label-size)
            validate_next_num "$1" "$2"
            T2PLOT_OPTS+=("$1" "$2")
            shift
            ;;
        -ks|--ksize|--k-size|--key-size|--tics-size)
            validate_next_num "$1" "$2"
            T2PLOT_OPTS+=("$1" "$2")
            shift
            ;;
        -ws|--wsize|--win-size|--window-size)
            validate_next_arg "$1" "$2"
            if [ -n "$(perl -pe 's/^[1-9][0-9]*,[1-9][0-9]*$//' <<< "$2")" ]; then
                printerr "Invalid argument for option '$1': expected width,height; found '$2'"
                abort_with_help
            fi
            T2PLOT_OPTS+=("$1" "$2")
            shift
            ;;
        -fs|--fullscreen)
            T2PLOT_OPTS+=("$1")
            ;;
        -c|--color)
            validate_next_arg "$1" "$2"
            if [ -n "$(perl -pe 's/^#[a-fA-F0-9]{6}$//' <<< "$2")" ]; then
                printerr "Invalid argument for option '$1': expected #rrggbb; found '$2'"
                abort_with_help
            fi
            T2PLOT_OPTS+=("$1" "$2")
            shift
            ;;
        -g|--grid)
            T2PLOT_OPTS+=("$1")
            ;;
        -lx|--log-x|-ly|--log-y|-lz|--log-z)
            T2PLOT_OPTS+=("$1")
            ;;
        -pl|--lines|-pt|--points)
            T2PLOT_OPTS+=("$1")
            ;;
        -r|--refresh)
            T2PLOT_OPTS+=("$1")
            if [ -n "$2" ] && [ -z "$(tr -d '0-9' <<< "$2")" ]; then
                T2PLOT_OPTS+=("$2")
                shift
            fi
            ;;

        -h|-\?|--help)
            usage
            exit 0
            ;;
        *)
            if [ ! -f "$1" ]; then
                abort_option_unknown "$1"
            fi
            FILE="$1"
            ;;
    esac
    shift
done

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

# Make sure the columns we need do exist
$TAWK 'BEGIN {
    _validate_col("flowInd")
    _validate_col("flowStat")
    _validate_col("L2L3L4Pl_Iat;L2L3L4Pl_Iat_nP")
    exit 0
}' "$FILE" || exit 1

# Prepare the filenames for the output files
NPS_FILE="$(replace_suffix "$FILE" ".txt" "_nps.txt")"
JMP_FILE="$(replace_suffix "$FILE" ".txt" "_iat_jmp.txt")"
SRT_FILE="$(replace_suffix "$NPS_FILE" ".txt" "_srt.txt")"
SMPL_FILE="$(replace_suffix "$SRT_FILE" ".txt" "_smpl.txt")"

printf "Generating '$NPS_FILE'... "
$TAWK -H -v edge="$EDG" -v fli="$FLI" -v statD="$DIR" -v Tm="$TM" -v invB="$INVB" -v srt="$SRT" '
    NR == 2 {
        if (Tm) {
            print "time", "PL"
        } else {
            print "sample", "PL"
        }

        if (L2L3L4Pl_Iat_nP != 0) {
            split($L2L3L4Pl_Iat_nP, A, ";")
        } else {
            split($L2L3L4Pl_Iat, A, ";")
        }

        split(A[1], B, "_")

        if (Tm && (strtonum(B[1]) != 0 || strtonum(B[2]) != 0)) {
            print "0.000000", "0"
        }
    }

    fli != "" && $flowInd != fli { next }

    {
        a = strtonum(substr($flowStat, 18, 1))
        if (statD != "" && a != statD) next

        if (L2L3L4Pl_Iat_nP != 0) {
            n = split($L2L3L4Pl_Iat_nP, A, ";")
            for (i = 1; i <= n; i++) {
                split(A[i], B, "_")
                if (invB && a == 1) B[1] = -B[1]
                if (Tm) {
                    printf "%f\t0\n", B[2]-edge, B[1]
                    printf "%f\t%d\n", B[2], B[1]
                    printf "%f\t%d\n", B[2]+B[3], B[1]
                    printf "%f\t0\n", B[2]+B[3]+edge, B[1]
                } else if (srt) {
                    printf "%f\t%d\n", B[2], B[1]
                } else {
                    printf "%d\t%d\n", tm++, B[1]
                }
            }
        } else {
            n = split($L2L3L4Pl_Iat, A, ";")
            for (i = 1; i <= n; i++) {
                split(A[i], B, "_")
                if (invB && a == 1) B[1] = -B[1]
                if (Tm || srt) {
                    printf "%f\t%d\n", B[2], B[1]
                } else {
                    printf "%d\t%d\n", tm++, B[1]
                }
            }
        }
        s = 0
    }' "$FILE" > "$NPS_FILE"
printok "OK"

if [ -n "$SRT" ] || [ -n "$smplIAT"  ]; then
    printf "Generating '$SRT_FILE'... "
    AWK 'NR != 1' "$NPS_FILE" | LC_ALL=C sort -t$'\t' -n -k1,1 |
        AWKF -v Tm="$TM" -v srt="$SRT" '
            BEGIN {
                spl = 0
                if (srt && !Tm) {
                    print "sample", "PL"
                } else {
                    print "time", "PL"
                }
            }
            {
                if (srt && !Tm) {
                    printf "%d\t%d\n", spl++, $2
                } else {
                    print
                }
            }' > "$SRT_FILE"
    printok "OK"
fi

if [ -n "$smplIAT" ]; then
    printf "Generating '$SMPL_FILE'... "
    AWKF -v Tm="$TM" -v srt="$SRT" -v smplIAT="$smplIAT" '
        BEGIN {
            n = 0
            if (srt && !Tm) {
                print "sample", "PL"
            } else {
                print "time", "PL"
            }
        }
        NR != 1 {
            for (i = n; i <= $1; i += smplIAT) {
                printf "%f\t%d\n", i, $2
            }
            n = i
        }' "$SRT_FILE" > "$SMPL_FILE"
    printok "OK"
fi

if [ -n "$JMP" ]; then
    printf "Generating '$JMP_FILE'... "
    cut -f 1 "$NPS_FILE" | sort -u | AWK '{
       b = $1 - a
       if (b > d) {
          d = b
          tmp = ($1 + d) / 2
          r = int(tmp)
          z = tmp - r
          #printf "NFRST_MINIATS: %d, NFRST_MINIATU: %d\n", r, int(1000000*z);
          printf "NFRST_MINIATS: %d, NFRST_MINIATU: %d, diff: %f \n", int($1), int(1000000*($1-int($1))), b
       }
       a = $1
    }' > "$JMP_FILE"
    printok "OK"
fi

if [ -n "$PLOT" ]; then
    "$T2PLOT" "${T2PLOT_OPTS[@]}" "$NPS_FILE"
fi
