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

usage() {
    printf "Usage:\n"
    printf "\t$0 file_nDPI.txt [-p=max%%] [-n=topN]\n\n"
    printf "Optional arguments:\n"
    printf "\t -p=P\tonly output protocols with probability higher than P%%.\n"
    printf "\t -n=N\tonly output top (N>0) or bottom (N<0) N protocols.\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}')

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;;
        *) echo "Unknown option $i"; exit 1;;
    esac
done

printf "Protocol ID\tPackets\tProbability[%%]\tDescription\n"
awk -F'\t' -v P="$P" '
        NR > 1 && $3 > P { print }
    ' "$FILE" | sort -nrk2 | $TOPFUNC -"$N"
echo
