#!/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), $UnixTimeFirst, $connSip }' f_flows.txt | t2plot
#   ./t2plot FILE_with_two_or_three_columns.txt

# 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

SNAME="$(basename "$0")"

printerr() {
    printf "\e[0;31mError: $1\e[0m\n" >&2
}

abort_with_help() {
    echo "Try '$SNAME --help' for more information."
    exit 1
}

# $1: name of the option
# $2: argument to validate
validate_args() {
    if [ -n "$2" ] && [ "${2:0:1}" != "-" ]; then
        return 0
    else
        printerr "Option '$1' requires an argument"
        abort_with_help
    fi
}

# $1: name of the option
# $2: argument to validate
validate_num() {
    if [ -n "$2" ] && [ -z "$(tr -d '[0-9]' <<< "$2")" ]; then
        return 0
    else
        printerr "Invalid argument for option '$1': expected number; found '$2'"
        abort_with_help
    fi
}

check_dependencies() {
    local deps="gnuplot"
    local pgrmname pgrmcmd
    type "$deps" &> /dev/null || {
        if hash apt-get 2> /dev/null; then
            pgrmname="apt-get"
            pgrmcmd="apt-get install"
        elif hash pacman 2> /dev/null; then
            pgrmname="pacman"
            pgrmcmd="pacman -S"
        elif hash yum 2> /dev/null; then
            pgrmname="yum"
            pgrmcmd="yum install"
        else
            pgrmname="your package utility"
        fi
        [ -n "$pgrmcmd" ] && pgrmcmd=": $pgrmcmd $deps"
        printerr "$SNAME: missing dependency: $deps"
        printf "You may use $pgrmname to install it$pgrmcmd\n"
        exit 1
    }
}

check_dependencies

while [ $# -ne 0 ]; do
    case "$1" in
        -t|--title)
            validate_args "$1" "$2"
            TITLE="$2"
            shift
            ;;
        -ts|--tsize|--t-size|--title-size)
            validate_args "$1" "$2"
            validate_num "$1" "$2"
            TSIZE="$2"
            shift
            ;;
        -ls|--lsize|--l-size|--label-size)
            validate_args "$1" "$2"
            validate_num "$1" "$2"
            LSIZE="$2"
            shift
            ;;
        -ks|--ksize|--k-size|--key-size|--tics-size)
            validate_args "$1" "$2"
            validate_num "$1" "$2"
            KSIZE="$2"
            shift
            ;;
        -ws|--wsize|--win-size|--window-size)
            validate_args "$1" "$2"
            if [ -z "$(sed 's/^[1-9][0-9]*,[1-9][0-9]*$//' <<< "$2")" ]; then
                WSIZE="$2"
                shift
            else
                printerr "Invalid argument for option '$1': expected width,height; found '$2'"
                abort_with_help
            fi
            ;;
        -fs|--fullscreen)
            WSIZE="$(xrandr | awk '/\*/ { sub(/x/, ","); print $1; exit }')"
            ;;
        -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)
            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 of the title [$TSIZE]"
            echo "    -ls           Size of the labels [$LSIZE]"
            echo "    -ks           Size of the keys/tics [$KSIZE]"
            echo
            echo "    -ws w,h       Window size (width,height) [$WSIZE]"
            echo "    -fs           Maximise window size (fullscreen)"
            echo
            echo "    -t title      Title of the plot [Tranalyzer2]"
            echo
            echo "    -h, --help    Show this help, then exit"
            exit 0;;
        *)
            if [ -f "$1" ]; then
                FILE="$1"
            else
                printerr "Unknown option '$1'"
                abort_with_help
            fi
    esac
    shift
done

if [ "$FILE" == "-" ] && ! readlink /proc/$$/fd/0 | grep -q "^pipe:"; then
    printerr "Input file is required"
    abort_with_help
fi

awk -F'\t' -v OFS='\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" '

BEGIN {
    print "set term qt title \"" title "\" size " wsize
    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"

    split("x,y,z", xyz, ",")
}

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

    # Use hex representation for Src/Dst IPv4
    for (i = 1; i <= NF; i++) {
        if ($i ~ /^SrcIP4x?$/ || $i ~ /^DstIP4x?$/) {
            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"
    exit
}

' "$FILE" | gnuplot -p
