#!/bin/bash
#
# 3D plot for connectionCounter
#
# Usage: ./gpcc [n NUM] [y IP_low IP_high] [hx] [lz]

# default values
N=8            # number of IP labels
Y0=0x00000000  # Lowest IP in y-axis
YN=0xffffffff  # Highest IP in y-axis
HX=0           # Whether to use IP (0) or hex (1) as labels
LZ=0           # Whether or not to use logscale for Z axis
FILE="-"

while [ $# -ne 0 ]; do
    case "$1" in
        hx)
            HX=1;;
        lz)
            LZ=1;;
        n)
            if [ -z "$2" ]; then exit 1; fi
            N="$2"; shift;;
        y)
            if [ -z "$2" ]; then exit 1; fi
            Y0="$2"; shift
            if [ -z "$2" ]; then exit 1; fi
            YN="$2"; shift;;
        h|-h|--help)
            echo "Usage:"
            echo "    $0 [OPTIONS...]"
            echo
            echo "Optional arguments:"
            echo "    d   NUM               number of elements to read"
            echo "    m   NUM               number of past values to display"
            echo "    n   NUM               number of IP labels (X tics)"
            echo "    y   IP_low IP_high    IP range to display"
            echo "    hx                    Use hex instead of IP as labels for X axis"
            echo "    lz                    Use logscale for Z axis"
            echo
            echo "    h                     Show this help, then exit"
            exit 0;;
	*)
		if [ -f "$1" ]; then
			FILE="$1"
		else
			echo "Unknown argument: $1"
		fi
    esac
    shift
done


# Ubuntu does not have the wxt term
if [ -n "$(grep Ubuntu /etc/issue)" ]; then
    GPTERM="qt"
else
    GPTERM="qt"
fi

if [ $LZ -eq 1 ]; then
    echo "set logscale z"
    zunit=" [log]"
fi

# Gnuplot configuration

awk -v n="$N" -v y0="$Y0" -v yn="$YN" -v iplabel="$HX" -v zunit="$zunit" '

BEGIN {
    print "set term x11 size 2000,1200 dashed background rgb \"white\" title \"Tranalyzer2\"";
    print "set title \"Anteaters Connection Counter\" font \"Times-Bold,20\"";
    print "set xlabel \"Time [s]\" offset -15 font \"Times-Bold,32\"";
    print "set ylabel \"IP Addresses\" offset 5 font \"Times-Bold,32\"";
    printf "set zlabel \"Connection Count %s\" offset -10 rotate by 90 font \"Times-Bold,32\"\n", zunit;
    print "set format y \"0x%08x\"";
    print "set zrange [0.001:*]";
    print "set key font \"Times-Bold,28\"";
    print "set tics font \"Times-Bold,28\"";
    print "set style data impulses";
    print "set view 67,116";
    title = "\"ConnectionCount = f(IP,time)\""; # title of the plot

    i = 0;
    k = 0;
    u = l = 0;

    y0 = ip2hex(y0)
    yn = ip2hex(yn)

    inc = (yn-y0)/n
    mask = and(compl(inc), 0xffffffff)

    delta = 32
    for (i = 0xf0000000; i > 0; i = rshift(i,4)) {
        delta -= 4;
        fmask += (rshift(and(mask, i), delta) != 0) ? i : 0;
    }

    if (iplabel) {
        # IP as labels
        for (i = y0; i < yn; i += inc) {
            net = and(i, fmask);
            p[1] = rshift(and(net, 0xff000000), 24);
            p[2] = rshift(and(net, 0x00ff0000), 16);
            p[3] = rshift(and(net, 0x0000ff00),  8);
            p[4] =        and(net, 0x000000ff);
            str = str ", \"" p[1] "." p[2] "." p[3] "." p[4] "\" " i
        }
        str = gensub(/^, /,"","",str);
        print "set ytics (" str ")";
    }

    print "set yrange [" y0 ":" yn "]";
    print "set ytics offset 5,-1 rotate by 90";
    print "splot \"-\" u 1:2:4 title"  title;
}

{
   split($8,A, "."); printf "%s\t0x%02x%02x%02x%02x\t%s\t%d\n", $4,A[1],A[2],A[3],A[4],$8,$82;
    print
    fflush()
}

END {
    print "e"
    print "pause 1000"
    fflush()
    exit
}

function ip2hex(ip) {
    if (ip ~ /0x[0-9a-fA-F]{1,8}/) {
        return strtonum(ip)
    } else if (ip ~ /[[:digit:]]{1,3}(\.[[:digit:]]{1,3}){3}/) {
        split(ip, tmp, /\./)
        return lshift(tmp[1], 24) + lshift(tmp[2], 16) + lshift(tmp[3], 8) + tmp[4]
    } else {
        print "Invalid format: " ip
        exit 1
    }
}
' "$FILE" | gnuplot -p
