#!/bin/bash
#
# Sort proto file for biggest/smallest talkers (in terms of number of packets)
#

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

usage() {
    printf "Usage:\n"
    printf "\t$SNAME file_protocols.txt [-p=max%%] [-n=topN] [-[l2,l4,tcp,udp,sctp]]\n\n"
    printf "Optional arguments:\n"
    printf "\t -p=P\tonly output ports/protocols with probability higher than P%%.\n"
    printf "\t -n=N\tonly output top (N>0) or bottom (N<0) N ports/protocols.\n"
    printf "\t -l2\tdo not output statistics for L2/3 protocols.\n"
    printf "\t -l4\tdo not output statistics for L4 protocols.\n"
    printf "\t -tcp\tdo not output statistics for TCP.\n"
    printf "\t -udp\tdo not output statistics for UDP.\n"
    printf "\t -sctp\tdo not output statistics for SCTP.\n"
    printf "\t -h\tdisplay this help, then exit.\n"
}

if [ ! -f "$1" ]; then
    usage
    exit 1
fi

FILE="$1"
shift
TOPFUNC=head
N=$(wc -l "$FILE" | awk '{print $1}')
L2=1;
L4=1;
PROTO=(TCP UDP SCTP)

for i in "$@"; do
    case $i in
        -h) usage; exit 0;;
        -p=*  ) P="${i#*=}"; shift;;
        -n=-* ) N="${i#*=-}"; TOPFUNC=tail; shift;;
        -n=*  ) N="${i#*=}"; shift;;
        -l2   ) L2=0; shift;;
        -l4   ) L4=0; shift;;
        -udp  ) PROTO=(${PROTO[@]/UDP/});  shift;;
        -tcp  ) PROTO=(${PROTO[@]/TCP/});  shift;;
        -sctp ) PROTO=(${PROTO[@]/SCTP/}); shift;;
        *) echo "Unknown option $i"; exit 1;;
    esac
done

if [ $L2 -eq 1 ] && [ ! -z "$(grep "L2/3" "$FILE")" ]; then
    printf "L2/3 Protocol\tPackets\tProbability[%%]\tDescription\n"
    awk -F'\t' -v P="$P" '
        $1 ~ /^0x/ && $3 > P { print }
        $0 ~ /^# L4/ { exit }
    ' "$FILE" | sort -nrk2 | $TOPFUNC -"$N"
    echo
fi

if [ $L4 -eq 1 ]; then
    printf "L4 Protocol\tPackets\tProbability[%%]\tDescription\n"
    awk -v P="$P" '
        $1 ~ /^0x/ { next }
        $1 ~ /^[0-9]/ && $3 > P { print }
        $0 ~ /^# Total TCP/ { exit }
    ' "$FILE" | sort -nrk2 | $TOPFUNC -"$N"
    echo
fi

for ((i = 0; i < ${#PROTO[@]}; i++)); do
    printf "${PROTO[i]} Port\tPackets\tProbability[%%]\tDescription\n"
    awk -v T="${PROTO[i]}" -v S="${PROTO[i+1]}" -v P="$P" '{
        if (A == 0 && $3 != T) next
        else A = 1
        if ($1 ~ /^[0-9]/ && $3 > P) print
        else if ($3 == S) exit
    }' "$FILE" | sort -nrk2 | $TOPFUNC -"$N"
    echo
done
