#!/bin/bash
#
# Generates sorted lists of all the columns (names or numbers) provided.
#

usage() {
    printf "Usage:\n"
    printf "\t$0 [-h|-e|-l] file_flows.txt <columns...>\n"
    printf "\t\t[-n=topN|-bottomN] [-p=min%%|-max%%]\n"
    printf "\t\t[-c=[f|p|b|colN]] [-f=\"filter\"] [icmp|tcp|udp]\n\n"
    printf "Columns can be specified as follows:\n"
    printf "\t- Column names, e.g., SrcIP4\n"
    printf "\t- Column numbers, e.g., 8\n"
    printf "\t- Ranges of column numbers, e.g., 8-11\n"
    printf "\t- Aggregation of column names, e.g., SrcPort:DstPort:L4Proto\n"
    printf "\t- Aggregation of column numbers, e.g., 8:10 or 8:10:11\n\n"
    printf "Optional arguments:\n"
    printf "\t-h\tdisplay this help, then exit\n"
    printf "\t-e\tdisplay some examples, then exit\n"
    printf "\t-l\tlist the column numbers and names, then exit\n"
    printf "\t-f=F\tonly display results which match the filter [EXPERIMENTAL]\n"
    printf "\t-c=C\tcompute statistics in terms of number of flows [default],\n"
    printf "\t\tpackets or bytes\n"
    printf "\t-n=N\tlimit the number of displayed results (> 0: topN, < 0: bottomN)\n"
    printf "\t-p=P\tonly display results whose probability is >= or <= than p%%\n\n"
    printf "Filters can be specified using the '-f' option or one of the following keywords:\n"
    printf "\ticmp\tonly display results for ICMP flows\n"
    printf "\ttcp\tonly display results for TCP flows\n"
    printf "\tudp\tonly display results for UDP flows\n"
}

examples() {
    printf "Examples:\n"
    printf "\tGenerate the list of the top 10 talkers (in terms of number of flows):\n"
    printf "\t\t./topNStat file_flows.txt -n=10 SrcIP4\n\n"
    printf "\tGenerate the list of the bottom 5 protocols:\n"
    printf "\t\t./topNStat file_flows.txt -n=-5 12\n\n"
    printf "\tGenerate the sorted lists of SrcIP4 and DstIP4 with probabilty >= 50%%:\n"
    printf "\t\t./topNStat file_flows.txt 7 9 -p=50\n\n"
    printf "\tGenerate the sorted lists of SrcPort and DstPort with prob. <= 10%%:\n"
    printf "\t\t./topNStat file_flows.txt SrcPort DstPort -p=-10\n\n"
    printf "\tGenerate the list of the top 5 SrcIP4,SrcPort,DstIP4,DstPort,L4Proto:\n"
    printf "\t\t./topNStat file_flows.txt 7-11 -n=5\n\n"
    printf "\tGenerate the sorted list of SrcIP4->DstIP4 pairs:\n"
    printf "\t\t./topNStat file_flows.txt 7:9\n\n"
    printf "\tGenerate the sorted list of SrcIP4->DstIP4->DstPort tuples:\n"
    printf "\t\t./topNStat file_flows.txt 7:9:10\n\n"
    printf "\tGenerate the sorted list of DstPort for UDP:\n"
    printf "\t\t./topNStat file_flows.txt 10 -f=\"11==17\"\n\n"
    printf "\tGenerate the sorted list of DstIP4 for UDP, DstPort 53:\n"
    printf "\t\t./topNStat file_flows.txt 9 -f=\"11 == 17 && 10 == 53\"\n\n"
    printf "\tGenerate the sorted list of SrcIP4 for TCP or UDP flows:\n"
    printf "\t\t./topNStat file_flows.txt 9 -f=\"L4Proto == 6 || L4Proto == 17\"\n\n"
    printf "\tCount the number of UDP or TCP flows with DstPort 80:\n"
    printf "\t\t# Filter is applied from left to right\n"
    printf "\t\t./topNStat file_flows.txt 9 -f=\"12==6 || 11==17 && 10==80\"\n\n"
    printf "\tGenerate the sorted lists of SrcPort and DstPort for UDP:\n"
    printf "\t\t# Count is based on the number of packets\n"
    printf "\t\t./topNStat file_flows.txt SrcPort DstPort udp -c=p\n"
}

listcols() {
    if [ -f "$FILE" ]; then
        awk -F'\t' -v OFS='\t' '
            /^%/ && $1 ~ /%[[:space:]]*dir$/ {
                sub(/^%[[:space:]]*/, "");
                for (i = 1; i <= NF; i++) {
                    print i, $i;
                }
                exit;
            }' "$FILE"
    else
        printf "Error: no flow file provided\n"
        exit 1
    fi
}

TOPFUNC=head

declare -a COLS

for i in "$@"; do
    case "$i" in
        -h) usage; exit 0;;
        -e) examples; exit 0;;
        -l) LISTCOLS=1;;
        -f=*) FILTER="${i#*=}";;
        -n=-*) N="${i#*=-}"; TOPFUNC=tail;;
        -n=*) N="${i#*=}";;
        -p=-*) MAXP="${i#*=-}";;
        -p=*) MINP="${i#*=}";;
        -c=*) C="${i#*=}";;
        # Ranges of column numbers
        [0-9]*-[0-9]*)
            i0=$(echo "$i" | cut -d- -f1)
            iN=$(echo "$i" | cut -d- -f2)
            COLS=("${COLS[@]}" "$(seq $i0 $iN)")
            ;;
        icmp) FILTER="L4Proto == 1";;
        tcp) FILTER="L4Proto == 6";;
        udp) FILTER="L4Proto == 17";;
        *)
            if [ -f "$i" ]; then
                FILE="$i"
            else
                COLS=("${COLS[@]}" "$i")
            fi
            ;;
    esac
    shift
done

if [ ! -z "$LISTCOLS" ]; then
    listcols
    exit 0
fi

if [ ${#COLS[@]} -eq 0 ] || [ ! -f "$FILE" ]; then
    usage
    exit 1
fi

if [ -z "$N" ]; then
    N=$(wc -l "$FILE" | cut -d' ' -f1)
fi

for i in ${COLS[@]}; do
    awk -F'\t' -v name="$i" -v count="$C" '
        /^%/ && $1 ~ /%[[:space:]]*dir$/ {
            sub(/^%[[:space:]]*/, "");
            split(name, n, ":");
            # check the column numbers
            for (i = 1; i <= length(n); i++) {
                if (n[i] ~ /^[0-9]+$/) {
                    if (n[i] > NF) {
                        printf "Error: column %d does not exist\n", n[i];
                        error = 1;
                    }
                } else {
                    found = 0;
                    for (c = 1; c <= NF; c++) {
                        if (n[i] == $c) {
                            found = 1;
                            n[i] = c;
                            break;
                        }
                    }
                    if (!found) {
                        printf "Error: column %s does not exist\n", n[i];
                        error = 1;
                    }
                }
            }
            if (count && count != "f") {
                if (count == "p") colname = "numPktsSnt";
                else if (count == "b") colname = "numBytesSnt";
                else if (count ~ /^[0-9]$/ && count <= NF) colname = $count;
                else colname = count;
                for (c = 1; c <= NF; c++) {
                    if ($c == colname) { found = 1; break }
                }
                if (!found) {
                    printf "Error: column %s does not exist\n", colname;
                    error = 1;
                }
            }
            if (!error) {
                # print column names
                printf "%s", $n[1];
                for (i = 2; i <= length(n); i++) {
                    printf ":%s", $n[i];
                }
            }
            exit(error);
        }' "$FILE"

    if [ $? -eq 1 ]; then
        continue
    fi
    printf "\tCount\tProbability[%%]\n"

    awk -F'\t' -v name="$i" -v filter="$FILTER" -v minP="$MINP" -v maxP="$MAXP" -v count="$C" '
        function chomp(s) {
            s = gensub(/^[[:space:]]*/, "", "", s); # remove leading spaces
            s = gensub(/[[:space:]]*$/, "", "", s); # remove trailing spaces
            return s;
        }

        BEGIN {
            if (!maxP) maxP = 100;
            split(filter, f, /[[:space:]]*[!=<>&|^]{1,2}[[:space:]]*/, seps);
            for (i = 1; i <= length(f); i++) f[i] = chomp(f[i]);
            for (i = 1; i <= length(seps); i++) seps[i] = chomp(seps[i]);
        }

        # Read column names
        /^%/ && $1 ~ /%[[:space:]]*dir$/ {
            sub(/^%[[:space:]]*/, "");
            split(name, n, ":");
            for (i = 1; i <= length(n); i++) {
                if (n[i] ~ /^[0-9]+$/) {
                    col[i] = n[i];
                } else {
                    for (c = 1; c <= NF; c++) {
                        if (n[i] == $c) {
                            col[i] = c;
                            break;
                        }
                    }
                }
            }
            for (i = 1; i <= length(f); i += 2) {
                if (f[i] !~ /^[0-9]+$/) {
                    # replace column names by numbers
                    for (c = 1; c <= NF; c++) {
                        if (f[i] == $c) {
                            f[i] = c;
                            break;
                        }
                    }
                }
            }
            if (count && count != "f") {
                if (count == "p") colname = "numPktsSnt";
                else if (count == "b") colname = "numBytesSnt";
                else if (count ~ /^[0-9]$/) colname = $count;
                else colname = count;
                for (c = 1; c <= NF; c++) {
                    if ($c == colname) { cc = c; break; }
                }
            }
            next;
        }

        !(/^%/ || /^#/) {
            if (count && count != "f") total += $cc;
            else total++;
            if (filter) {
                j = 1;
                for (s = 1; s <= length(f); s += 2) {
                    a = $strtonum(f[s]);
                    b = f[s+1];
                    r[j] = 0;
                    switch (seps[s]) {
                        case "==": if (a == b) r[j] = 1; break;
                        case "!=": if (a != b) r[j] = 1; break;
                        case ">=": if (a >= b) r[j] = 1; break;
                        case "<=": if (a <= b) r[j] = 1; break;
                        case ">" : if (a >  b) r[j] = 1; break;
                        case "<" : if (a  < b) r[j] = 1; break;
                        case "&" : if (and(strtonum(a), strtonum(b))) r[j] = 1; break;
                        case "|" : if (or (strtonum(a), strtonum(b))) r[j] = 1; break;
                        case "^" : if (xor(strtonum(a), strtonum(b))) r[j] = 1; break;
                    }
                    j++;
                }
                j = 1;
                res = r[j++];
                for (s = 2; s <= length(seps); s += 2) {
                    switch (seps[s]) {
                        case "&&": res = res && r[j]; break;
                        case "||": res = res || r[j]; break;
                        default: res = 0; break; # invalid filter => false
                    }
                    j++;
                }
                if (!res) next;
            }
            key = $col[1];
            for (i = 2; i <= length(col); i++) {
                key = key ":" $col[i];
            }
            if (count && count != "f") array[key] += $cc;
            else array[key]++;
        }

        END {
            if (total) {
                for (k in array) {
                    p = 100*array[k]/total;
                    if (p >= minP && p <= maxP) printf "%s\t%d\t%9.6f\n", k, array[k], p;
                }
            }
        }
    ' "$FILE" | sort -rnk2 -t$'\t' | $TOPFUNC -"$N"
    echo
done

unset -v COLS
