#!/bin/bash
#
# 2D/3D plot for Tranalyzer2
#
# Usage: t2plot [OPTION...] <FILE>
#
# Format of the input file:
#   - First row is the header (column names)
#   - Two or three columns
#
# Example:
#   tawk '{ print ip2num($srcIP4), ip2num($dstIP4) }' f_flows.txt | t2plot -pt
#   tawk '{ print ip2num($srcIP4), $timeFirst, $connSip }' f_flows.txt | t2plot
#   t2plot FILE_with_two_or_three_columns.txt

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

check_dependency gnuplot

# default values
LX=0     # Whether or not to use logscale for X axis
LY=0     # Whether or not to use logscale for Y axis
LZ=0     # Whether or not to use logscale for Z axis
GRID=0   # Whether or not to display a grid in the background
FILE="-"
TITLE="Tranalyzer2"
STYLE="impulses"

WSIZE="800,600"  # Window size (width, height)
TSIZE=16         # title size
LSIZE=10         # label size
KSIZE=8          # key/tics size

DEFAULT_REFRESH=5 # Refreshing the graph is required for mouse interaction

usage() {
    echo "Usage:"
    echo "    $SNAME [OPTION...] <FILE>"
    echo
    echo "Optional arguments:"
    echo "    -lx           Use logscale for X axis"
    echo "    -ly           Use logscale for Y axis"
    echo "    -lz           Use logscale for Z axis"
    echo
    echo "    -pt           Use points instead of impulses"
    echo
    echo "    -g            Display a grid in the background"
    echo
    echo "    -ts size      Size of the title [$TSIZE]"
    echo "    -ls size      Size of the labels [$LSIZE]"
    echo "    -ks size      Size of the keys/tics [$KSIZE]"
    echo
    echo "    -ws w,h       Window size (width,height) [$WSIZE]"
    echo "    -fs           Maximise window size (fullscreen)"
    echo
    echo "    -r [num]      Refresh the graph every num-seconds [$DEFAULT_REFRESH]"
    echo
    echo "    -t title      Title of the plot [$TITLE]"
    echo
    echo "    -h, --help    Show this help, then exit"
}

while [ $# -ne 0 ]; do
    case "$1" in
        -t|--title)
            validate_next_arg "$1" "$2"
            TITLE="$2"
            shift
            ;;
        -ts|--tsize|--t-size|--title-size)
            validate_next_num "$1" "$2"
            TSIZE="$2"
            shift
            ;;
        -ls|--lsize|--l-size|--label-size)
            validate_next_num "$1" "$2"
            LSIZE="$2"
            shift
            ;;
        -ks|--ksize|--k-size|--key-size|--tics-size)
            validate_next_num "$1" "$2"
            KSIZE="$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
            WSIZE="$2"
            shift
            ;;
        -fs|--fullscreen)
            WSIZE="$(xrandr | $AWK '/\*/ { sub(/x/, ","); print $1; exit }')"
            ;;
        -r)
            if [ -n "$2" ] && [ -z "$(tr -d '0-9' <<< "$2")" ]; then
                REFRESH="$2"
                shift
            else
                REFRESH="$DEFAULT_REFRESH"
            fi
            ;;
        -g|--grid) GRID=1;;
        -lx|--log-x) LX=1;;
        -ly|--log-y) LY=1;;
        -lz|--log-z) LZ=1;;
        -pt|--points) STYLE="points";;
        -h|-\?|--help) usage; exit 0;;
        *)
            if [ ! -f "$1" ]; then
                abort_option_unknown "$1"
            fi
            FILE="$1"
            ;;
    esac
    shift
done

if [ "$FILE" == "-" ] && [ -t 0 ]; then
    abort_required_file
fi

$AWK -F"\t" -v lx="$LX" -v ly="$LY" -v lz="$LZ" -v style="$STYLE" \
      -v title="$TITLE" -v tsize="$TSIZE" -v lsize="$LSIZE" \
      -v ksize="$KSIZE" -v wsize="$WSIZE" -v grid="$GRID" \
      -v refresh="$REFRESH" '

BEGIN {
    print "set term qt title \"" title "\" size " wsize " persist"
    print "set title \"" title "\" font \"Times-Bold," tsize "\""
    print "set style data " style
    print "set key font \"Times-Bold," ksize "\""
    print "set tics font \"Times-Bold," ksize "\""

    if (grid) print "set grid"

    if (lx) print "set logscale x"
    if (ly) print "set logscale y"
    if (lz) print "set logscale z"
}

NR == 1 {
    if (NF != 2 && NF != 3) {
        print "Error: input must have 2 or 3 columns"
        exit
    }

    # Use hex representation for src/dst IPv4
    split("xyz", xyz, "")
    for (i = 1; i <= NF; i++) {
        if ($i ~ /^srcIP4$/ || $i ~ /^dstIP4$/) {
            print "set format " xyz[i] " \"0x%08x\""
        }
    }

    printf "set xlabel \"" $1 "%s\" font \"Times-Bold," lsize "\"\n", lx ? " [log]" : ""
    printf "set ylabel \"" $2 "%s\" font \"Times-Bold," lsize "\"\n", ly ? " [log]" : ""

    if (NF == 2) {
        print "plot \"-\" u 1:2 notitle with " style
    } else {
        printf "set zlabel \"" $3 "%s\" rotate by 90 font \"Times-Bold," lsize "\"\n", lz ? " [log]" : ""
        print "splot \"-\" u 1:2:3 notitle with " style
    }
    next
}

{
    print
}

END {
    print "e"
    # Refresh the graph every "refresh" seconds
    if (refresh) {
        while (1) {
            print "pause " refresh
            print "replot"
        }
    }
}

' "$FILE" | gnuplot
