#!/usr/bin/env bash
#
# The protStat script can be used to sort the '_protocols.txt'} file (generated
# by the protoStats plugin) or the '_nDPI.txt' file (generated by the nDPI
# plugin) for the most or least occurring protocols (in terms of number of
# packets or bytes). In addition, it can also sort the '_icmpStats.txt' and
# '_igmpStats.txt' files (generated by the icmpDecode and igmpDecode plugins
# respectively). It can output the top or bottom N protocols or only those
# with at least a given percentage.

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

usage() {
    printf "Usage:\n"
    printf "    $SNAME [OPTION...] file_protocols.txt\n"
    printf "    $SNAME [OPTION...] file_nDPI.txt\n"
    printf "    $SNAME [OPTION...] file_icmpStats.txt\n"
    printf "    $SNAME [OPTION...] file_igmpStats.txt\n"
    printf "\n"
    printf "Optional arguments:\n"
    printf "    -b              sort and filter by bytes instead of packets\n"
    printf "    -r              sort in reverse order\n"
    printf "\n"
    printf "    -B              do not output bytes counts\n"
    printf "    -P              do not output packets counts (automatically sort by bytes)\n"
    printf "    -C              do not output percentages\n"
    printf "\n"
    printf "    -p P            only output rows with probability >=P%% (P>0) or <=P%% (P<0)\n"
    printf "    -n N            only output top (N>0) or bottom (N<0) N ports/protocols\n"
    printf "\n"
    printf "    -H              output raw numbers [default]\n"
    printf "    -HR             output human readable numbers\n"
    printf "    -HH             output raw and human readable numbers\n"
    printf "\n"
    printf "    -l2             only output statistics for L2/3 protocols\n"
    printf "    -l4             only output statistics for L4 protocols\n"
    printf "    -tcp            only output statistics for TCP\n"
    printf "    -udp            only output statistics for UDP\n"
    printf "    -udplite        only output statistics for UDP-Lite\n"
    printf "    -sctp           only output statistics for SCTP\n"
    printf "\n"
    printf "    -icmp           only output statistics for ICMP\n"
    printf "    -icmpv6         only output statistics for ICMPv6\n"
    printf "\n"
    printf "    -igmp           only output statistics for IGMP\n"
    printf "\n"
    printf "    -ndpi           only output statistics for nDPI\n"
    printf "\n"
    printf "    --color[=WHEN]  colorize the output; WHEN can be 'always' (default\n"
    printf "                    if omitted), 'auto', or 'never' [default: 'auto']\n"
    printf "\n"
    printf "Help and documentation arguments:\n"
    printf "    -h, --help      display this help, then exit\n"
}

get_header() {
    case "$1" in
        ICMP)     echo "ICMP Type";;
        ICMPv6)   echo "ICMPv6 Type";;
        IGMP)     echo "IGMP Type";;
        NDPI)     echo "Protocol ID";;
        L2)       echo "L2/3 Protocol";;
        L4)       echo "L4 Protocol";;
        SCTP)     echo "SCTP Port";;
        TCP)      echo "TCP Port";;
        UDP)      echo "UDP Port";;
        UDP-Lite) echo "UDP-Lite Port";;
    esac
}

# Default values
COLWIDTH=30
HRNUM=2     # 0: human readable, 1: raw and human readable, 2: raw
TOPFUNC=head
SORDER="r"
PROTO=()
P0=0
PN=100

if [ -t 1 ]; then
    COLOR=1
else
    COLOR=0
fi

while [ $# -gt 0 ]; do
    case "$1" in
        -b|--bytes)
            BYTES=1
            ;;

        -r|--reverse)
            unset SORDER
            ;;

        -B|--no-bytes)
            NOBYTES=1
            ;;
        -P|--no-packets)
            BYTES=1
            NOPKTS=1
            ;;
        -C|--no-percentages)
            NOPERCENT=1
            unset COLWIDTH
            ;;

        -HR|--hrnum)
            HRNUM=0
            ;;
        -HH|--raw-and-hrnum)
            HRNUM=1
            ;;
        -H|--raw-numbers)
            HRNUM=2
            ;;

        # -p=-P, -p=P, -pP -p-P, -p P, -p -P
        -p=-*)
            P0=0
            PN="${1#*=-}"
            validate_next_float "-p" "-$PN"
            ;;
        -p-*)
            P0=0
            PN="${1#*p-}"
            validate_next_float "-p" "-$PN"
            ;;
        -p=*)
            P0="${1#*=}"
            PN=100
            validate_next_float "-p" "$P0"
            ;;
        -p)
            validate_next_float "$1" "$2"
            if [ $2 -ge 0 ]; then
                P0="$2"
                PN=100
            else
                P0=0
                PN="$((-$2))"
            fi
            shift
            ;;
        -p*)
            P0="${1#*p}"
            PN=100
            validate_next_float "-p" "$P0"
            ;;

        # -n=-N, -n=N, -nN, -n-N, -n N, -n -N
        -n=-*)
            N="${1#*=-}"
            TOPFUNC=tail
            validate_next_int "-n" "-$N"
            ;;
        -n-*)
            N="${1#*n-}"
            TOPFUNC=tail
            validate_next_int "-n" "-$N"
            ;;
        -n=*)
            N="${1#*=}"
            validate_next_int "-n" "$N"
            ;;
        -n)
            validate_next_int "$1" "$2"
            if [ $2 -ge 0 ]; then
                N="$2"
            else
                N="$((-$2))"
                TOPFUNC=tail
            fi
            shift
            ;;
        -n*)
            N="${1#*n}"
            validate_next_int "-n" "$N"
            ;;

        -*l2     ) PROTO+=(L2);;
        -*l4     ) PROTO+=(L4);;
        -*icmp   ) PROTO+=(ICMP);;
        -*icmpv6 ) PROTO+=(ICMPv6);;
        -*igmp   ) PROTO+=(IGMP);;
        -*ndpi   ) PROTO+=(NDPI);;
        -*tcp    ) PROTO+=(TCP);;
        -*udp    ) PROTO+=(UDP);;
        -*udplite) PROTO+=(UDP-Lite);;
        -*sctp   ) PROTO+=(SCTP);;

        --color=always) COLOR=1;;
        --color=never) COLOR=0;;
        --color=auto) ;;
        --color)
            if [ -z "$2" ] || arg_is_option "$2"; then
                COLOR=1
            elif [ "$2" = "always" ]; then
                COLOR=1
                shift
            elif [ "$2" = "never" ]; then
                COLOR=0
                shift
            elif [ "$2" = "auto" ]; then
                shift
            fi
            ;;

        -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 [ -n "$BYTES" ] && [ -n "$NOBYTES" ]; then
    printerr "Cannot sort by bytes without outputing bytes count"
    printinf "Remove one or both of '-b' and '-B' options"
    exit 1
fi

if [ -n "$NOPKTS" ] && [ -n "$NOBYTES" ]; then
    printerr "Cannot exclude both bytes and packets counts"
    printinf "Remove one or both of '-B' and '-P' options"
    exit 1
fi

if [ $COLOR = 0 ]; then
    unset BOLD
    unset NOCOLOR
fi

if [ -n "$(grep -F -e "# ICMP Type" -e "# ICMPv6 Type" "$FILE")" ]; then
    TEMP="${PROTO[*]}"
    PROTO=()
    [ -n "$(grep -Fw ICMP <<< "$TEMP")" ] && PROTO+=(ICMP)
    [ -n "$(grep -Fw ICMPv6 <<< "$TEMP")" ] && PROTO+=(ICMPv6)
    [ -z "$PROTO" ] && PROTO=(ICMP ICMPv6)
elif [ -n "$(grep -F "# IGMP Type" "$FILE")" ]; then
    PROTO=(IGMP)
elif [ -n "$(grep "# Protocol ID" "$FILE")" ]; then
    PROTO=(NDPI)
else
    TEMP="${PROTO[*]}"
    PROTO=()
    for i in L2 L4 TCP UDP UDP-Lite SCTP; do
        [ -n "$(grep -Fw "$i" <<< "$TEMP")" ] && PROTO+=("$i")
    done
    [ -z "$PROTO" ] && PROTO=(L2 L4 TCP UDP UDP-Lite SCTP)
fi

# Number of rows
[ -z "$N" ] && N=$(wc -l "$FILE" | AWK '{print $1}')

# Common headers (not applicable for I[CG]MP)
PRI_CHDR="${BOLD}%s\t"
if [ -z "$NOPKTS" ]; then
    PRI_CHDR="${PRI_CHDR}%${COLWIDTH}s\t"
    CHDR+=("Packets")
fi
if [ -z "$NOBYTES" ]; then
    PRI_CHDR="${PRI_CHDR}%${COLWIDTH}s\t"
    CHDR+=("Bytes")
fi
PRI_CHDR="${PRI_CHDR}%s${NOCOLOR}\n"
CHDR+=("Description")

# Column to use for sorting and comparing probabilities (not applicable for I[CG]MP)
if [ -n "$BYTES" ]; then
    if [ -z "$NOPKTS" ]; then
        SCOL=3
    else
        SCOL=2
    fi
    PCOL="bytes"
else
    SCOL=2
fi

if [ -n "$(grep -Fw -e "ICMP" -e "ICMPv6" -e "IGMP" <<< "${PROTO[*]}")" ]; then
    for ((i = 0; i < ${#PROTO[@]}; i++)); do
        HDR="$(get_header "${PROTO[i]}")"
        printf "${BOLD}$HDR\tCode\t%${COLWIDTH}s${NOCOLOR}\n" "Packets"
        AWK -F"\t" -v protoname="$HDR" -v P0="$P0" -v PN="$PN" '
            $0 ~ "# " protoname { printing = 1; next }
            printing == 0 { next }
            $0 ~ /^\s*$/ { exit }
            {
                match($3, /^\s*([0-9]+) \[\s*(.*)%\]$/, pkts)
                p = pkts[2]
                if (P0 <= p && p <= PN) {
                    printf "%s\t%s\t%s\n", $1, $2, $3
                }
                next
            }
        ' "$FILE" | sort -t$'\t' -n${SORDER}k3 | $TOPFUNC -"$N" | $TAWK -t -H \
            -v hrnum_mode=$HRNUM -v nopercent="$NOPERCENT" -v colwidth="$COLWIDTH" '{
                printf "%s\t%s\t", $1, $2
                if (nopercent) {
                    printf "%s\t", hrnum($3, hrnum_mode)
                } else {
                    match($3, /^\s*([0-9]+) \[\s*(.*)%\]$/, pkts)
                    printf "%*s [%6.02f%%]\t", colwidth, hrnum(pkts[1], hrnum_mode), pkts[2]
                }
                printf "\n"
            }'
        echo
    done
else
    for ((i = 0; i < ${#PROTO[@]}; i++)); do
        HDR="$(get_header "${PROTO[i]}")"
        if [ "$(grep -F "# $HDR" "$FILE")" ]; then
            printf "$PRI_CHDR" "$HDR" "${CHDR[@]}"
            AWK -F"\t" -v protoname="$HDR" -v pcol="$PCOL" \
                       -v P0="$P0" -v PN="$PN" -v nopkts="$NOPKTS" \
                       -v nobytes="$NOBYTES" -v nopercent="$NOPERCENT" '
                $0 ~ "# " protoname { printing = 1; next }
                printing == 0 { next }
                $0 ~ /^\s*$/ { exit }
                {
                    match($2, /^\s*([0-9]+) \[\s*(.*)%\]$/, pkts)
                    match($3, /^\s*([0-9]+) \[\s*(.*)%\]$/, bytes)
                    p = (pcol == "bytes") ? bytes[2] : pkts[2]
                    if (P0 <= p && p <= PN) {
                        printf "%s\t", $1
                        if (!nopkts) {
                            if (nopercent) printf "%s\t", pkts[1]
                            else printf "%s\t", $2
                        }
                        if (!nobytes) {
                            if (nopercent) printf "%s\t", bytes[1]
                            else printf "%s\t", $3
                        }
                        print $4
                    }
                    next
                }
            ' "$FILE" | sort -t$'\t' -n${SORDER}k$SCOL | $TOPFUNC -"$N" |
                $TAWK -t -H -v hrnum_mode=$HRNUM -v nopkts="$NOPKTS" \
                            -v colwidth="$COLWIDTH" -v nobytes="$NOBYTES" \
                            -v nopercent="$NOPERCENT" '{
                    printf "%s\t", $1
                    if (!nopkts) {
                        if (nopercent) {
                            printf "%s\t", hrnum($2, hrnum_mode)
                        } else {
                            match($2, /^\s*([0-9]+) \[\s*(.*)%\]$/, pkts)
                            printf "%*s [%6.02f%%]\t", colwidth, hrnum(pkts[1], hrnum_mode), pkts[2]
                        }
                    }
                    if (!nobytes) {
                        if (nopercent) {
                            printf "%s\t", hrnum($3, hrnum_mode)
                        } else {
                            match($3, /^\s*([0-9]+) \[\s*(.*)%\]$/, bytes)
                            printf "%*s [%6.02f%%]\t", colwidth, hrnum(bytes[1], hrnum_mode), bytes[2]
                        }
                    }
                    print $4
                }'
            echo
        fi
    done
fi
