#!/bin/sh
#
# Extracts ICMP and parent flows from a flow file.
#
# Usage: icmpX [OPTION...] file_flows.txt

ALL=0  # 0: only ICMP flows with parents
       # 1: all ICMP flows and parents
IDX=0  # 0: print entire flows
       # 1: Only print flow indices
HDR=1  # 0: do not print the header (columns name)
       # 1: print the header (columns name)

USAGE() {
    echo "icmpX - Extracts ICMP and parent flows for a flow file"
    echo
    echo "Usage: $0 [OPTION...] file_flows.txt"
    echo
    echo "Optional arguments:"
    echo "    -a    extract all ICMP flows (with or without parents)"
    echo "          (default: only ICMP flows with parents)" 
    echo "    -i    only print flow indexes (default: print the whole flow)" 
    echo "    -n    do not print the header (columns name)" 
    echo "    -h    display this help, then exit"
}

for i in "$@"; do
    case "$i" in
        -h) USAGE; exit 0;;
        -a) ALL=1;;
        -i) IDX=1;;
        -n) HDR=0;;
         *)
            if [ -f "$i" ] && [ -z "$INFILE" ] ; then
                INFILE="$i"
            else
                echo "Unknown option $i"; echo; USAGE; exit 1
            fi
            ;;
    esac
done 

if [ ! -f "$INFILE" ]; then
    echo "Input file is required"
    echo
    USAGE
    exit 1
fi

awk -F'\t' -v OFS='\t' -v all=$ALL -v idx=$IDX -v hdr=$HDR '

/^#/ {
    next; # skip comments
}

# Read column names
NR == FNR && /^%/ && $1 ~ /%[[:space:]]*dir$/ {
    for (i = 1; i <= NF; i++) {
        if ($i == "flowInd") flowInd = i;
        else if ($i == "L4Proto") L4Proto = i;
        else if ($i == "icmpPFindex") icmpPFindex = i
    }
    if (flowInd == 0 || L4Proto == 0 || icmpPFindex == 0) {
        # one of the required columns could not be found
        exit        
    }
}

# Print header
NR != FNR && /^%/ && $1 ~ /%[[:space:]]*dir$/ && hdr == 1 && idx == 0 {
    print
    next
}

/^%/ {
    next; # skip special comments
}

NR == FNR && $L4Proto == 1 {
    if (all == 1) {
        if (idx == 1) {
            if ($icmpPFindex > 0) print $icmpPFindex
            print $flowInd
        } else {
            fidx[$flowInd] = 1;
            if ($icmpPFindex > 0) fidx[$icmpPFindex] = 1;
        }
    } else {
        if ($icmpPFindex > 0) {
            if (idx == 1) {
                print $icmpPFindex "\n" $flowInd
            } else {
                fidx[$icmpPFindex] = 1;
                fidx[$flowInd] = 1;
            }
        }
    }
    next
}

NR != FNR && idx == 1 {
    exit
}

# Print the flows
NR != FNR && $flowInd in fidx {
    print
}

' "$INFILE" "$INFILE"
