#!/usr/bin/env bash
#
# 2D/3D plot for Tranalyzer2
#
# Usage: t2plot [OPTION...] <FILE>
#
# Format of the input file:
#   - First row MUST be the header (column names), may start with a '%'
#   - One, two or more columns tab separated
#   - Column(s) to plot can be selected with -o option
#
# TODO
#   - add option to sort distribution by labels
#   - add support for multiple graphs
#   - add option to save temporary files and gnuplot scripts
#   - add option to plot mean, mode, ...

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

check_dependency gnuplot

usage() {
    echo "Usage:"
    echo "    $SNAME [OPTION...] <FILE>"
    echo
    echo "Optional arguments:"
    echo "    -F sep            Input field separator [\"\\t\"]"
    echo "    -o x:y[:z]        Order of columns to display, e.g., 1:2 or 2:1:3"
    echo
    echo "    -H binwidth       Bin data and plot histogram"
    echo "    -D[=ORDER]        Plot distribution with textual labels; ORDER can be"
    echo "                          'r' to sort the values in reverse order"
    echo "                          'l' to sort the distribution by labels"
    echo "                          'lr' to sort the distribution by labels in reverse"
    echo
    echo "    -lx               Use logscale for X axis"
    echo "    -ly               Use logscale for Y axis"
    echo "    -lz               Use logscale for Z axis"
    echo
    echo "    -pl               Use lines instead of impulses"
    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 "    -sx begin:end     Set x range"
    echo "    -sy begin:end     Set y range"
    echo "    -sz begin:end     Set z range"
    echo
    echo "    -rx angle         Rotate x labels by 'angle' degrees (2D only)"
    echo "    -ry angle         Rotate y labels by 'angle' degrees (2D only)"
    echo
    echo "    -v rotx,rotz      View of graphics, e.g., 60,30"
    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 "    -tx               Label for X axis"
    echo "    -ty               Label for Y axis"
    echo "    -tz               Label for Z axis"
    echo
    echo "    -c color          Color of the plot [$COLOR]"
    echo
    echo "    --no-title        Hide the plot main title"
    echo
    echo "    -t title          Main title of the plot [$TITLE]"
    echo "    -s title          Subtitle of the plot [$SUBTITLE]"
    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 "    -e, --examples    Show usage examples, then exit"
    echo "    -h, --help        Show this help, then exit"
}

examples() {
    echo

    printinf "# Plot data from a file with 1, 2 or 3 columns"
    printf "t2plot FILE_with_one_two_or_three_columns.txt\n\n"

    printinf "# Plot columns 26 and 28 from a file with many columns"
    printf "t2plot -o \"26:28\" file_with_many_columns.txt\n\n"

    printinf "# Plot columns 'numBytesSnt' and 'numBytesRcvd' from a file with many columns"
    printf "t2plot -o \"numBytesSnt:numBytesRcvd\" file_with_many_columns.txt\n\n"

    printinf "# Plot the distribution of packet sizes between 0 and 40"
    printf "t2plot -o numPktsSnt -sx \"0:40\" f_flows.txt\n\n"

    printinf "# Plot the distribution of sent bytes per country"
    printf "t2plot -D -o srcIPCC:numBytesSnt f_flows.txt\n\n"

    printinf "# Plot the distribution of bytes among protocols"
    printf "tawk '{ print proto(), \$numBytesSnt }' f_flows.txt | t2plot -D\n\n"

    printinf "# Plot source and destination IP"
    printf "tawk '{ print shost(), dhost() }' f_flows.txt | t2plot -pt\n\n"

    printinf "# Plot source IP, time, and number of connections from this source IP"
    printf "tawk '{ print \$srcIP, \$timeFirst, \$connSip }' f_flows.txt | t2plot\n\n"

    printinf "# Plot the distribution of packets over TCP ports"
    printf "protStat -tcp -B -C f_protocols.txt | t2plot -D\n\n"
}

cleanup() {
    [ -f "$TEMPFILE" ] && [ -z "$KEEP_TEMP" ] && rm "$TEMPFILE"
    local ret=$1
    if [ "$(pgrep -P $$ | wc -l)" -gt 1 ]; then
        printinf "Killing all subprocesses..."
        kill -- -$$
    fi
    exit $ret
}

# default values
FS=$'\t'
FILE="-"
TITLE="Tranalyzer2"
STYLE="impulses"
COLOR="#ff1c00"
TERM="qt"

# -D option
SORDER="r"  # sort order
STYPE="n"   # numeric sort
SNUM=2      # sort by labels (1) or values (2)

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

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

# options
while [ $# -ne 0 ]; do
    case "$1" in

        -tx|--xlabel)
            validate_next_arg "$1" "$2"
            TX="$2"
            shift
            ;;
        -ty|--ylabel)
            validate_next_arg "$1" "$2"
            TY="$2"
            shift
            ;;
        -tz|--zlabel)
            validate_next_arg "$1" "$2"
            TZ="$2"
            shift
            ;;

        -s|--subtitle)
            validate_next_arg "$1" "$2"
            SUBTITLE="$2"
            shift
            ;;
        -t|--title)
            validate_next_arg "$1" "$2"
            TITLE="$2"
            shift
            ;;
        --no-title)
            unset TITLE
            ;;

        -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
            SETX="$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
            SETY="$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
            SETZ="$2"
            shift
            ;;

        -o|--order)
            validate_next_arg "$1" "$2"
            if [ -n "$(perl -pe 's/^[[:alnum:]_]+(:[[:alnum:]_]+){0,2}$//' <<< "$2")" ]; then
                printerr "Invalid argument for option '$1': expected x, x:y or x:y:z; found '$2'"
                abort_with_help
            fi
            ORDER="$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
            VIEW="$2"
            shift
            ;;

        -rx|--rotate-x-labels)
            validate_next_int "$1" "$2"
            RX="$2"
            shift
            ;;
        -ry|--rotate-y-labels)
            validate_next_int "$1" "$2"
            RY="$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)
            if [ "$(uname)" = "Darwin" ]; then
                WSIZE="$(system_profiler SPDisplaysDataType | AWK '/^\s*Resolution:/ { print $2/2 "," $4/2; exit }')"
            else
                WSIZE="$(xrandr | AWK '/\*/ { sub(/x/, ","); print $1; exit }')"
            fi
            ;;

        -r|--refresh)
            if [ -n "$2" ] && [ -z "$(tr -d '0-9' <<< "$2")" ]; then
                REFRESH="$2"
                shift
            else
                REFRESH="$DEFAULT_REFRESH"
            fi
            ;;

        -D|--distribution)
            STYLE="histograms"
            HISTO="1"
            DISTRIBUTION=1
            ;;
        -D=r|-D=rev|-D=reversed)
            STYLE="histograms"
            HISTO="1"
            DISTRIBUTION=1
            unset SORDER
            ;;
        -D=l|-D=labels)
            STYLE="histograms"
            HISTO="1"
            DISTRIBUTION=1
            SNUM=1
            unset STYPE
            ;;
        -D=lr|-D=l-r|-D=labels-r|-D=labels-rev|-D=labels-reversed)
            STYLE="histograms"
            HISTO="1"
            DISTRIBUTION=1
            SNUM=1
            unset SORDER
            unset STYPE
            ;;

        -H|--histo)
            validate_next_num "$1" "$2"
            STYLE="histograms"
            HISTO="$2"
            shift
            ;;

        -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
            COLOR="$2"
            shift
            ;;

        -F)
            validate_next_arg "$1" "$2"
            FS="$2"
            shift
            ;;

        --gif|--jpeg|--png|--svg)
            validate_next_arg "$1" "$2"
            TERM="${1#*--}"
            IMGFILE="$2"
            shift
            ;;

        -g|--grid) GRID=1;;
        -lx|--log-x) LX=1;;
        -ly|--log-y) LY=1;;
        -lz|--log-z) LZ=1;;
        -pl|--points) STYLE="lines";;
        -pt|--points) STYLE="points";;
        -e|--examples) examples; exit 0;;
        -h|-\?|--help) usage; exit 0;;
        *)
            if [ ! -f "$1" ]; then
                abort_option_unknown "$1"
            fi
            FILE="$1"
            ;;
    esac
    shift
done

if [ -t 0 ] && [ -p /dev/stdin ]; then
    if [ -z "$FILE" ]; then
        abort_required_file
    elif [ ! -f "$FILE" ]; then
        printerr "$FILE does not exist or is not a regular file"
        abort_with_help
    fi
fi

# Setup signal handler
trap "trap - SIGTERM && cleanup 1" HUP INT QUIT TERM
trap "cleanup \$?" EXIT

# Extract the header (first line)
if [ -f "$FILE" ]; then
    HEADER="$(head -1 "$FILE")"
else
    HEADER="$(read -r line; echo "$line")"
fi

# Remove the leading '%' if present
HEADER="$(AWK '{ gsub(/^%\s*/, "") }; 1' <<< "$HEADER")"

if [ -z "$ORDER" ]; then
    NF=$(AWK -F "$FS" '{ print NF }' <<< "$HEADER")
    case $NF in
        3) ORDER="1:2:3";;
        2) ORDER="1:2";;
        *) ORDER="1";;
    esac
fi

validate_columns() {
    echo "$HEADER" | AWK -F "$FS" -v ord="$ORDER" -i "$T2HOME/scripts/tawk/funcs/strip" -i "$T2HOME/scripts/tawk/funcs/printerr" '{
        # Mapping column name -> column numbers
        for (i = 1; i <= NF; i++) {
            COLNUM[strip($i)] = i
        }

        _ordsize = split(ord, _ord, ":")
        for (i = 1; i <= _ordsize; i++) {
            _ordnum = (match(_ord[i], /^[0-9]+$/) ? _ord[i] : COLNUM[_ord[i]])
            if (!_ordnum || _ordnum > NF) {
                printerr("Column \"" _ord[i] "\" does not exist")
                exit(1)
            }
        }
    }'
}

if ! validate_columns; then
    exit 1
fi

if [ -n "$DISTRIBUTION" ]; then
    TEMPFILE="$(mktemp)"
    $TAWK -F "$FS" -v OFS="$FS" -t -H -v ord="$ORDER" \
          -v header="$HEADER" -v tempfile="$TEMPFILE" '
        BEGIN {
            # Mapping column name -> column numbers
            nf = split(header, _header, FS)
            for (i = 1; i <= nf; i++) {
                _header[i] = strip(_header[i])
                COLNUM[_header[i]] = i
            }

            _ordsize = split(ord, _ord, ":")
            for (i = 1; i <= _ordsize; i++) {
                _ordnum[i] = (match(_ord[i], /^[0-9]+$/) ? _ord[i] : COLNUM[_ord[i]])
            }

            str = _header[_ordnum[1]]
            if (_ordsize == 1) {
                str = str OFS "Count"
            } else {
                for (i = 2; i <= _ordsize; i++) {
                    str = str OFS _header[_ordnum[i]]
                }
            }

            print str > tempfile
        }
        {
            val = strip($(_ordnum[1]))
            if (_ordsize > 1) {
                bin[val] += strip($(_ordnum[2]))
            } else {
                bin[val]++
            }
        }

        END {
            for (val in bin) {
                print val, bin[val]
            }
        }' "$FILE" | sort -${STYPE}${SORDER}k${SNUM} >> "$TEMPFILE"
    FILE="$TEMPFILE"
    HEADER="$(head -1 "$FILE")"
    ORDER="1:2"
fi

if [ -f "$FILE" ]; then
    HAS_HEADER=1
fi

$TAWK -F "$FS" -t \
        -v lx="$LX" -v ly="$LY" -v lz="$LZ" \
        -v sx="$SETX" -v sy="$SETY" -v sz="$SETZ" \
        -v vw="$VIEW" -v ord="$ORDER" -v style="$STYLE" \
        -v rx="$RX" -v ry="$RY" \
        -v tx="$TX" -v ty="$TY" -v tz="$TZ" \
        -v subtitle="$SUBTITLE" -v title="$TITLE" -v tsize="$TSIZE" \
        -v lsize="$LSIZE" -v ksize="$KSIZE" -v wsize="$WSIZE" -v grid="$GRID" \
        -v histo="$HISTO" -v distrib="$DISTRIBUTION" -v color="$COLOR" \
        -v header="$HEADER" -v has_header="$HAS_HEADER" -v refresh="$REFRESH" \
        -v term="$TERM" -v imgfile="$IMGFILE" '

    function init_gnuplot() {
        print "set term " term " size " wsize ((refresh || imgfile) ? "" : " persist")
        if (imgfile) print "set output \"" imgfile "\""
        if (title) 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 "\""
        print "set ticslevel 0"

        if (grid) print "set grid"

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

        if (sx) print "set xrange[" sx "]"
        if (sy) print "set yrange[" sy "]"
        if (sz) print "set zrange[" sz "]"

        if (vw) print "set view " vw

        # Mapping column name -> column numbers
        nf = split(header, _header, FS)
        for (i = 1; i <= nf; i++) {
            _header[i] = strip(_header[i])
            COLNUM[_header[i]] = i
        }

        _ordsize = split(ord, _ord, ":")
        for (i = 1; i <= _ordsize; i++) {
            _ordnum[i] = (match(_ord[i], /^[0-9]+$/) ? _ord[i] : COLNUM[_ord[i]])
        }

        # Use hex representation for src/dst IPv4
        split("xyz", xyz, "")
        for (i = 1; i <= _ordsize; i++) {
            v = _ordnum[i]
            if (_header[v] ~ /^srcIP[46]?$/ || _header[v] ~ /^dstIP[46]?$/) {
                print "set format " xyz[i] " \"0x%08x\""
                to_convert[i] = v
            }
        }

        if (!tx) tx = _header[_ordnum[1]]
        if (!ty) ty = (_ordsize == 1) ? "Count" : _header[_ordnum[2]]

        if (subtitle) {
            subtitle = "title \"" subtitle "\""
        } else {
            subtitle = "notitle"
        }

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

        if (rx) print "set xtics rotate by " rx " right"
        if (ry) print "set ytics rotate by " ry " center"

        if (histo || nf == 1 || _ordsize == 1) {
            init_histo()
        }

        if (distrib) {
            print "plot \"-\" u (bin($2)):($3):xticlabel(1) with boxes lc \"" color "\" " subtitle
        } else if (histo) {
            # If only one column was provided, count the number of occurences.
            # Otherwise sum up the values
            _val = (_ordsize == 2) ? "$2" : 1.0
            print "plot \"-\" u (bin($1)):(" _val ") smooth freq with boxes lc \"" color "\" " subtitle
        } else if (_ordsize == 2) {
            print "plot \"-\" u 1:2 " subtitle " with " style " lc \"" color "\""
        } else {
            if (!tz) tz = _header[_ordnum[3]]
            printf "set zlabel \"" tz "%s\" rotate by 90 font \"Times-Bold," lsize "\"\n", lz ? " [log]" : ""
            print "splot \"-\" u 1:2:3 " subtitle " with " style " lc \"" color "\""
        }
    }

    function init_histo() {
        if (!histo) {
            histo = 1
            print "set style data histograms"
        }
        print "set style fill solid 0.5"
        print "binwidth = " histo
        print "set boxwidth (binwidth * 0.9) absolute"
        print "bin(x) = binwidth * floor(x / binwidth) + binwidth / 2.0"
    }

    BEGIN {
        init_gnuplot()
    }

    (NR == 1 && has_header) || /^[%#]/ {
        next
    }

    {
        str = ""
        for (i = 1; i <= _ordsize; i++) {
            val = strip($(_ordnum[i]))
            if (i == 1 && distrib) {
                if (!(val in bin)) {
                    bin[val] = cnt++
                }
                str = str "\t\"" val "\""
                val = bin[val]
            } else if (to_convert[i]) {
                val = ip2num(strip(val))
            } else {
                val = strip(val)
            }
            str = str "\t" val
        }

        printf "%s\n", str
    }

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

    ' "$FILE" | gnuplot &

wait < <(jobs -p)
