#!/usr/bin/env bash
#
# Transform packet size (PS) and inter-arrivel times (IAT) statistics in
# flow file to gnuplot format

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

usage() {
    echo "Usage:"
    echo "    $SNAME [OPTION...] <FILE_flows.txt>"
    echo
    echo "Optional arguments:"
    echo "    --iat            Generate inter-arrivel times (IAT) distribution only"
    echo "    --ps             Generate packet size (PS) distribution only"
    echo "    --ps-iat         Generate PS-IAT distribution only"
    echo
    echo "    -P               Plot the signals"
    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 "Help and documentation arguments:"
    echo "    -h, --help       Show this help, then exit"
}

generate_2d_signal() {
    local idx1 idx2 outfile
    local name="$1"
    if [ "$name" = "IAT" ]; then
        idx1=2
        idx2=5
        outfile="$IAT_FILE"
    else
        idx1=1
        idx2=4
        outfile="$PS_FILE"
    fi
    printf "Generating '$outfile'... "
    printf "$name\tCount\n" > "$outfile"
    $TAWK -t -H '{ print $Ps_Iat_Cnt_PsCnt_IatCnt }' "$FILE" | tr ';' '\n' |
        AWK -v idx1=$idx1 -v idx2=$idx2 '!/^#|^%|.*:.*|^$/ {
            split($1, A, "_")
            printf "%d\t%d\n", A[idx1], A[idx2]
        }' | sort -n | uniq | AWK -F'\t' -v OFS='\t' '
            NR == 1 {
                A = $1
            }
            $1 == A {
                sum += $2
                A = $1
                next
            }
            {
                print A, sum
                A = $1
                sum = $2
            }
            END {
                print A, sum
            }
        ' >> "$outfile"
    printok "OK"
}

generate_3d_signal() {
    local name1="$1"
    local name2="$2"
    local idx1=1
    local idx2=2
    local idx3=3
    local outfile="$PS_IAT_FILE"
    printf "Generating '$outfile'... "
    printf "$name1\t$name2\tCount\n" > "$outfile"
    $TAWK -t -H '{ print $Ps_Iat_Cnt_PsCnt_IatCnt }' "$FILE" | tr ';' '\n' |
        AWK -v idx1=$idx1 -v idx2=$idx2 -v idx3=$idx3 '!/^#|^%|.*:.*|^$/ {
            split($1, A, "_")
            printf "%d\t%d\t%d\n", A[idx1], A[idx2], A[idx3]
        }' | sort -n | uniq | AWK -F'\t' -v OFS='\t' '
            NR == 1 {
                A = $1
                B = $2
            }
            $1 == A && $2 == B {
                sum += $3
                A = $1
                B = $2
                next
            }
            {
                print A, B, sum
                A = $1
                B = $2
                sum = $3
            }
            END {
                print A, B, sum
            }
        ' >> "$outfile"
    printok "OK"
}

while [ $# -ne 0 ]; do
    case "$1" in
        --iat) IAT=1;;
        --ps) PS=1;;
        --ps-iat) PS_IAT=1;;
        -P|--plot) PLOT=1;;
        --gif|--jpeg|--png|--svg)
            validate_next_arg "$1" "$2"
            T2PLOT_OPTS+=("$1" "$2")
            shift
            ;;
        -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

# If no distribution was specified, generate them all
if [ -z "${PS}${IAT}${PS_IAT}" ]; then
    PS=1
    IAT=1
    PS_IAT=1
fi

DISTRIB="${PS}${IAT}${PS_IAT}"
if [ ${#DISTRIB} -ne 1 ]; then
    printerr "Can only generate SVG file for one distribution"
    printinf "Use one of --iat, --ps or --ps-iat option."
    exit 1
fi

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

if [ -n "$PS" ]; then
    PS_FILE="$(replace_suffix "$FILE" ".txt" "_ps.txt")"
    generate_2d_signal "PS"
fi

if [ -n "$IAT" ]; then
    IAT_FILE="$(replace_suffix "$FILE" ".txt" "_iat.txt")"
    generate_2d_signal "IAT"
fi

if [ -n "$PS_IAT" ]; then
    PS_IAT_FILE="$(replace_suffix "$FILE" ".txt" "_ps_iat.txt")"
    generate_3d_signal "PS" "IAT"
fi

if [ $PLOT ] || [ $T2PLOT_OPTS ]; then
    if [ -n "$PS" ] && [ -f "$PS_FILE" ]; then
        "$T2PLOT" ${T2PLOT_OPTS[*]} "$PS_FILE"
    fi
    if [ -n "$IAT" ] && [ -f "$IAT_FILE" ]; then
        "$T2PLOT" ${T2PLOT_OPTS[*]} "$IAT_FILE"
    fi
    if [ -n "$PS_IAT" ] && [ -f "$PS_IAT_FILE" ]; then
        "$T2PLOT" ${T2PLOT_OPTS[*]} "$PS_IAT_FILE"
    fi
fi
