#!/bin/bash
#
# TODO check for duplicate column names

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

usage() {
    printf "Usage:\n"
    printf "    $SNAME [OPTION...] 'program' file_flows.txt\n"
    printf "    $SNAME [OPTION...] -I file_flows.txt 'program'\n\n"
    printf "Optional arguments:\n"
    printf "    -I file             Alternative way to specify the input file\n"
    printf "    -s char             First character for the row listing the columns name\n"
    printf "    -F fs               Use 'fs' for the input field separator\n"
    printf "    -n                  Load nfdump functions\n"
    printf "    -e                  Load examples\n"
    printf "    -X xerfile          Specify the .xer file to use with -k and -x options\n"
    printf "    -x outfile          Run the fextractor on the extracted data\n"
    printf "    -k                  Run Wireshark on the extracted data\n"
    printf "    -t                  Do not validate column names\n"
    printf "    -H                  Do not output the header (column names)\n"
    printf "    -c[=u]              Output command line as a comment\n"
    printf "                        (use -c=u for UTC instead of localtime)\n\n"
    printf "Help and documentation arguments:\n"
    printf "    -l[=n], --list[=n]  List column names and numbers\n"
    printf "    -g[=n], --func[=n]  List available functions\n\n"
    printf "    -d fname            Display function 'fname' documentation\n"
    printf "    -V vname[=value]    Display variable 'vname' documentation\n\n"
    printf "    -D                  Display tawk PDF documentation\n\n"
    printf "    -?, -h, --help      Show help options and exit\n"
}

_printerr() {
    printf "\e[0;31m$1\e[0m\n" >&2  # Red
}

_printok() {
    printf "\e[0;32m$1\e[0m\n"      # Green
}

_printwrn() {
    printf "\e[0;33m$1\e[0m\n" >&2  # Orange
}

_printinf() {
    printf "\e[0;34m$1\e[0m\n"      # Blue
}

_abort_with_help() {
    printf "Try '$SNAME --help' for more information.\n"
    exit 1
}

# $1: name of the option
# $2: argument to validate
_validate_next_arg() {
    if [ -n "$2" ] && [ "${2:0:1}" != "-" ]; then
        return 0
    else
        _printerr "Option '$1' requires an argument"
        _abort_with_help
    fi
}

_get_wireshark() {
    local wshark=wireshark
    type $wshark &> /dev/null || wshark=wireshark-qt
    type $wshark &> /dev/null || {
        type wireshark-gtk &> /dev/null && wshark=wireshark-gtk
    }
    echo "$wshark"
}

_check_dependencies_osx() {
    type gawk greadlink gsed wireshark &> /dev/null || {
        local deps="coreutils gawk gnu-sed wireshark"
        _printerr "Missing dependencies: $deps"
        _printinf "You may use homebrew to install them: brew install coreutils"
        exit 1
    }

    AWK="$(which gawk)"
    READLINK="$(which greadlink)"
    OPEN="$(which open)"
    SED="$(which gsed)"
    WIRESHARK="$(which wireshark)"
}

_check_dependencies_linux() {
    local wshark="$(_get_wireshark)"
    local deps="coreutils gawk sed $wshark xdg-utils"
    local pgrmname pgrmcmd
    type gawk readlink sed "$wshark" &> /dev/null || {
        if hash apt-get 2> /dev/null; then
            pgrmname="apt-get"
            pgrmcmd="apt-get install"
        elif hash pacman 2> /dev/null; then
            pgrmname="pacman"
            pgrmcmd="pacman -S"
        elif hash yum 2> /dev/null; then
            pgrmname="yum"
            pgrmcmd="yum install"
        else
            pgrmname="your package utility"
        fi
        [ -n "$pgrmcmd" ] && pgrmcmd=": $pgrmcmd $deps"
        _printerr "Missing dependencies: $deps"
        _printinf "You may use $pgrmname to install them$pgrmcmd"
        exit 1
    }

    AWK="$(which gawk)"
    OPEN="$(which xdg-open)"
    READLINK="$(which readlink)"
    SED="$(which sed)"
    WIRESHARK="$(which "$wshark")"
}

_check_awk_version() {
    local gver="$($AWK --version | $AWK '{ print $3; exit }')"
    if [[ $gver < 4.1 ]]; then
        _printerr "Minimum gawk version required is 4.1, found '$gver'"
        exit 1
    fi
    if [ -z "$($AWK -h | grep "^\s\+-M\s\+--bignum$")" ]; then
        _printwrn "Your gawk version does not support bignum: IPv6 handling may be buggy"
    fi
}

_check_dependencies() {
    if [ "$(uname)" = "Darwin" ]; then
        _check_dependencies_osx
    else
        _check_dependencies_linux
    fi
    _check_awk_version
}

_cleanup() {
    if [ -z "$1" ]; then
        printerr "cleanup: missing return code (cleanup retcode)"
        exit 1
    fi

    local ret=$1

    #_printinf "Cleaning temporary files"
    rm -f "$TEMPFILE"

    exit $ret
}

# Check for required programs
_check_dependencies

# Set TAWKHOME
if [ -n "$ZSH_VERSION" ]; then
    TAWKHOME="$(dirname "$($READLINK -f "${(%):-%x}")")"
else
    TAWKHOME="$(dirname "$($READLINK -f "$BASH_SOURCE")")"
fi

FEXTRACTOR="$($READLINK -f "$TAWKHOME/../../findexer/fextractor/fextractor")"

list_names() {
    local cnt=1
    local d="${1:-1}"
    local table=$(
        for i in ${names[@]}; do
            printf "%3d\t%s" $cnt $i
            if [ $((d > 1 ? cnt%d : 0)) -eq 0 ]; then
                printf "\n"
            else
                printf "\t"
            fi
            cnt=$((cnt+1))
        done)
    printf "%s\n" "$table" | column -t -s $'\t'
}

list_funcs() {
    local cnt=1
    local d="${1:-1}"
    local dir=("$TAWKHOME/funcs/")
    dir+=("$TAWKHOME/t2custom/")
    [ $NFDUMP ] && dir+=("$TAWKHOME/t2nfdump/")
    [ $EXAMPLES ] && dir+=("$TAWKHOME/examples/")
    local funcs=($(find "${dir[@]}" -maxdepth 1 -type f ! -name '*.load' ! -name '.*'))
    if [ -z "$funcs" ]; then
        _printerr "No functions available"
        exit 1
    fi
    local table=$(
        for i in ${funcs[@]}; do
            i="$($AWK -F'/' '{ print $NF }' <<< "$i")"
            printf "%s" $i
            if [ $((d > 1 ? cnt%d : 0)) -eq 0 ]; then
                printf "\n"
            else
                printf "\t"
            fi
            cnt=$((cnt+1))
        done | sort)
    printf "%s\n" "$table" | column -t -s $'\t'
}

validate_names() {
    local array=()

    # Extract all variable names from 'program'
    for i in $ARGS; do
        while [ -n "$(grep "\$[a-zA-Z0-9_]\+" <<< "$i")" ]; do
            local n="$($SED 's/[^$]*\$\([a-zA-Z0-9_]\+\).*/\1/' <<< "$i")"
            i="$($SED 's/[^$]*\$[a-zA-Z0-9_]\+\(.*\)/\1/' <<< "$i")"
            if [ -z "$($SED 's/^[0-9]\+$//' <<< "$n")" ] || [ "$n" = "NF" ]; then
                # do not validate $0,$1,..., $NF
                continue
            else
                array+=($n)
            fi
        done
    done

    local start=${#array[@]}
    local stop
    if [ -n "$ZSH_VERSION" ]; then
        # zsh arrays start at 1... d'oh!
        stop=1
    else
        start=$((start-1))
        stop=0
    fi

    # Make sure all variables exist
    for ((i = $start; i >= $stop; i--)); do
        for j in ${names[@]}; do
            if [ "${array[i]}" = "$j" ]; then
                if [ -n "$ZSH_VERSION" ]; then
                    array[$i]=()
                else
                    unset array[$i]
                fi
                break
            fi
        done
    done

    if [ ${#array[@]} -ne 0 ]; then
        for i in ${array[@]}; do
            _printerr "Column '$i' not found"
            for j in ${names[@]}; do
                if [ "$(fgrep -i "$i" <<< "$j")" ]; then
                    _printinf "Did you mean '$j'?"
                fi
            done
        done
        exit 1
    fi
}

funcdoc() {
    local fname="$1"
    # Extract the function name and parameters excluding the local variables (separated from the parameters by 8 spaces)
    local func="$($SED -n "s/^function\s\+\($fname(.*\)).*/\1/p" "$TAWKHOME/"*"/$fname" | $AWK -F"        " '{ gsub(",$", "", $1); print $1 ")" }')"
    if [ -z "$func" ]; then
        func="$fname"
    fi
    printf "\e[1;33m$func:\e[0m\n\n" # Bold, Orange
    $AWK '
        /^[^#]/ { exit }
        NR > 2 { gsub(/^#/, " "); print }
    ' "$TAWKHOME/"*"/$fname"
}

doc() {
    local fnames="$1"
    if [ "$1" = "all" ] || [ "$fnames" = "funcs" ]; then
        fnames="$(ls "$TAWKHOME/funcs/"* | $AWK -F'/' '{print $NF}' | grep -v funcs.load | xargs | tr ' ' ',')"
    fi
    if [ "$1" = "all" ] || [ "$fnames" = "examples" ]; then
        fnames="$fnames,$(ls "$TAWKHOME/examples/"* | $AWK -F'/' '{print $NF}' | grep -v examples.load | xargs | tr ' ' ',')"
    fi
    if [ "$1" = "all" ] || [ "$fnames" = "t2nfdump" ]; then
        fnames="$fnames,$(ls "$TAWKHOME/t2nfdump/"* | $AWK -F'/' '{print $NF}' | grep -v t2nfdump.load | xargs | tr ' ' ',')"
    fi
    for i in $(tr ',' ' ' <<< "$fnames"); do
        if [ "$i" = "examples" ] || [ "$i" = "t2nfdump" ]; then
            continue
        fi
        if [ -f "$TAWKHOME/examples/$i" ] ||
           [ -f "$TAWKHOME/funcs/$i" ]    ||
           [ -f "$TAWKHOME/t2nfdump/$i" ]
        then
            funcdoc "$i"
        else
            _printerr "No documentation available for function '$i'"
        fi
    done
}

vdoc() {
    local vname="$1"
    local name="$(cut -d= -f1 <<< "$vname")"
    local val="$(cut -s -d= -f2 <<< "$vname")"
    if [ ! -f "$TAWKHOME/vars/$name" ]; then
        _printerr "No documentation available for variable '$name'"
        exit 1
    fi
    # variable name in bold and orange
    printf "The \e[1;33m$name\e[0m column "
    if [ -n "$val" ]; then
        printf "with value \e[1;01m$val\e[0m "
    fi
    printf "is to be interpreted as follows:\n\n"
    $AWK -v OFS='|' -F'|' -v val="$val" -i "$TAWKHOME/funcs/rstrip" '
        BEGIN   { vval = strtonum(val) }
        /^#H/   { COLOR = "\033[1;01m" } # Header, bold
        /^#I/   { COLOR = "\033[0;34m" } # Info, blue
        /^#W/   { COLOR = "\033[0;33m" } # Warning, orange
        /^#E/   { COLOR = "\033[0;31m" } # Error, red
        /^[^#]/ { COLOR = "\033[0;00m" } # Default
        {
            gsub(/^#./, "  ")
            # Print headers and all the rows if no value specified
            pri = (NR < 3 || !vval)
            if (!pri) {
                # Only two columns: value and description
                if (NF == 2) {
                    pri = ($1 == vval)
                # Three columns: bit, hex value and description
                } else {
                    hex = strtonum(gensub(/\s+/, "", "g", $2))
                    pri = and(hex, vval)
                }
            }
            if (pri) {
                printf "%s%s\033[0m\n", COLOR, $0
            }
        }
    ' "$TAWKHOME/vars/$name"
}

# Default values
HDRSEP="%" # First character for the row listing the columns name
FS=$'\t'   # Field Separator
OFS=$'\t'  # Output Field Separator
PRIHDR=1   # Keep the column names
VALIDATE_NAMES=1

while [ $# -gt 0 ]; do
    case "$1" in
        -F|--field-separator)
            _validate_next_arg "$1" "$2"
            FS="$2"
            shift
            ;;
        -s|--special-header)
            # Comment out the following line to force the row with
            # the column names to start with a special character
            #_validate_next_arg "$1" "$2"
            HDRSEP="$2"
            shift
            ;;
        -c|-c=*|--comment=*|--comment)
            COMMENT=1
            if [ "${1#*=}" = "u" ]; then
                UTC="-u"
            fi
            ;;
        -H|--no-header) PRIHDR=0;;
        -t) unset VALIDATE_NAMES;;
        -e|--examples) EXAMPLES=1;;
        -n|--nfdump) NFDUMP=1;;
        -l|--list) LIST_NAMES=1;;
        -l=*|--list=*)
            LIST_NAMES="${1#*=}"
            if [ -z "$LIST_NAMES" ] || [ -n "$(tr -d '0-9' <<< "$LIST_NAMES")" ]; then
                _printerr "Option '${1%=*}' requires a numeric argument"
                _abort_with_help
            fi
            ;;
        -g|--func) LIST_FUNCS=1;;
        -g=*|--func=*)
            LIST_FUNCS="${1#*=}"
            if [ -n "$(tr -d '0-9' <<< "$LIST_FUNCS")" ]; then
                _printerr "Option '${1%=*}' requires a numeric argument"
                _abort_with_help
            fi
            ;;
        -k|--wireshark) WSHARK=1;;
        -X|--xer-file)
            _validate_next_arg "$1" "$2"
            XER_FILE="$2"
            shift
            ;;
        -x|--fextractor)
            _validate_next_arg "$1" "$2"
            OUT_FILE="$2"
            FEXTRACT=1
            shift
            ;;
        -d|--doc)
            _validate_next_arg "$1" "$2"
            DOC+=("$2")
            shift
            ;;
        -V|--var)
            _validate_next_arg "$1" "$2"
            VDOC+=("$2")
            shift
            ;;
        -I|--input)
            _validate_next_arg "$1" "$2"
            FILE+=("$2")
            IOPTION=1
            shift
            ;;
        -D)
            if [ ! -f "$TAWKHOME/doc/tawk.pdf" ]; then
                _printerr "tawk.pdf not found in $TAWKHOME/doc/"
                exit 1
            fi
            "$OPEN" "$TAWKHOME/doc/tawk.pdf"
            exit 0
            ;;
        -\?|-h|--help)
            usage
            exit 0
            ;;
        # awk options with file as arguments
        -i|--include|-f|--file)
            ARGS+=("$1")
            if [ -f "$2" ]; then
                ARGS+=("$2")
                shift
            fi
            ;;
        *)
            if [ -f "$1" ] && [ -z "$FILE" ] && [ $# -eq 1 ]; then
                FILE="$1"
            else
                ARGS+=("$1")
            fi
            ;;
    esac
    shift
done

if [ -n "$DOC" ]; then
    for i in "${DOC[@]}"; do
        doc "$i"
    done
    exit 0
fi

if [ -n "$VDOC" ]; then
    for i in "${VDOC[@]}"; do
        vdoc "$i"
    done
    exit 0
fi

if [ $LIST_FUNCS ]; then
    list_funcs "$LIST_FUNCS"
    exit 0
fi

if [ -n "$FEXTRACT" ] && [ ! -f "$FEXTRACTOR" ]; then
    _printerr "fextractor not found"
    exit 1
fi

if [ -t 0 ] && [ -p /dev/stdin ]; then
    if [ -z "$FILE" ]; then
        _printerr "Input file is required"
        _abort_with_help
    elif [ ! -f "$FILE" ]; then
        _printerr "$FILE does not exist or is not a regular file"
        _abort_with_help
    fi
fi

if [ -f "$FILE" ]; then
    names=($($AWK -i $TAWKHOME/funcs/hdr -F"$FS" -v OFS="$FS" -v __HDRSEP__="$HDRSEP" '
        hdr() {
            # Remove leading __HDRSEP__
            if (match(__HDRSEP__, /^(.*)NR\s*==\s*[0-9]+$/, _n)) {
                gsub("^" _n[1] "\\s*", "", $1)
            } else {
                gsub("^"__HDRSEP__ "\\s*", "", $1)
            }
            print
            exit
        }' "$FILE" | tr ' (){}[] -./' '_'))
    if [ -z "$names" ] && { [ $LIST_NAMES ] || [ $VALIDATE_NAMES ]; }; then
        _printerr "Column names not found"
        _printinf "Use '-t' option to ignore this error"
        exit 1
    fi

    if [ $VALIDATE_NAMES ]; then
        # Check that no column name matches a function name (slow)
        FUNCS="$(list_funcs)"
        for i in ${!names[@]}; do
            REDEFINED="$(grep -w -F "${names[$i]}" <<< "$FUNCS")"
            if [ -n "$REDEFINED" ]; then
                #_printerr "A function named '${names[$i]}' already exists."
                # Append an underscore to avoid name collision
                names[$i]+="_"
            fi
        done
    fi

    if [ $LIST_NAMES ]; then
        list_names "$LIST_NAMES"
        exit 0
    fi

    if [ $VALIDATE_NAMES ]; then
        validate_names
    fi

    if [ -n "$FEXTRACT$WSHARK" ]; then
        if [ -z "$XER_FILE" ]; then
            XER_FILE="$($AWK -F. -v OFS=. 'NF>1 {
                # _packets.txt -> _flows.xer
                gsub(/_packets$/, "_flows", $(NF-1))
                # _packets_cc.txt -> _flows.xer
                # _flows_dns.txt  -> _flows.xer
                gsub(/_(flows|packets)_[^_]+$/, "_flows", $(NF-1))
                # Keep trailing numbers (-W option)
                match($NF, /([0-9]+)$/, idx)
                $NF = "xer" idx[1]
            } { print }' <<< "$FILE")"
        fi
        if [ ! -f "$XER_FILE" ]; then
            _printerr "Could not find '$XER_FILE'"
            exit 1
        fi
    fi
fi

if [ -f "$FILE" ] && [ ! -t 0 ]; then
    # Reading from stdin
    unset FILE
fi

if [ -z "$ARGS" ]; then
    _printerr "Program is required"
    _abort_with_help
fi

# Default gawk options
OPTS=(
    -M -v PREC=256
    -v __PRIHDR__=$PRIHDR
)

trap "trap - SIGTERM && _cleanup 1" HUP INT QUIT TERM
trap "_cleanup 0" EXIT

# Prepare mapping between columns name and number
TEMPFILE=`(tempfile) 2> /dev/null` || TEMPFILE=/tmp/tawk$$
echo "BEGIN {" > "$TEMPFILE"
CNT=1
for i in ${names[@]}; do
    echo "$i = $CNT" >> "$TEMPFILE"
    CNT=$((CNT+1))
done
echo "}" >> "$TEMPFILE"

# Load mapping column names/numbers
OPTS+=(-i "$TEMPFILE")

# Load tawk functions
AWKPATH="$TAWKHOME/funcs/"
OPTS+=(-i "$TAWKHOME/funcs/funcs.load")

if [ $NFDUMP ]; then
    AWKPATH="${AWKPATH}:$TAWKHOME/t2nfdump/"
    OPTS+=(-i "$TAWKHOME/t2nfdump/t2nfdump.load");
fi

if [ $EXAMPLES ]; then
    AWKPATH="${AWKPATH}:$TAWKHOME/examples/"
    OPTS+=(-i "$TAWKHOME/examples/examples.load");
fi

if [ -f "$TAWKHOME/t2custom.load" ] && [ -n "$($AWK '/^@include/' "$TAWKHOME/t2custom.load")" ]; then
    AWKPATH="${AWKPATH}:$TAWKHOME/t2custom/"
    OPTS+=(-i "$TAWKHOME/t2custom/t2custom.load")
fi

if [ $COMMENT ]; then
    printf "# Generated with $SNAME from '${FILE:-stdin}'\n"
    printf "# Date: $(date $UTC +"%FT%T%z")"
    if [ "$(fgrep -e '-v ' -e '-i ' <<< "${ARGS[*]}")" ]; then
        printf "\n# Variables and libraries used:"
        for i in ${ARGS[*]}; do
            if [[ $i = '-i' ]] || [[ $i = '-v' ]]; then
                _v=1
                printf " %s" "$i"
            elif [ "$_v" ]; then
                printf " %s" "$i"
                unset _v
            fi
        done
    fi
    printf "\n# Filter used:"
    for i in ${ARGS[*]}; do
        if [[ "$i" = '-i' ]] || [[ "$i" = '-v' ]]; then
            _v=1
        elif [ "$_v" ]; then
            unset _v
        else
            printf " %s" "$i"
        fi
    done
    printf "\n"
fi

export AWKPATH

if [ -z "$FEXTRACT$WSHARK" ]; then
    $AWK ${OPTS[*]} -F"$FS" -v OFS="$OFS" -v __HDRSEP__="$HDRSEP" "${ARGS[@]}" "${FILE[@]}"
elif [ ! -f "$FILE" ]; then
    _printerr "Input file is required"
    _abort_with_help
else
    FEX_OPTS=(-b -f -i -)
    if [ -z "$WSHARK" ]; then
        $AWK ${OPTS[*]} -F"$FS" -v OFS="$OFS" -v __HDRSEP__="$HDRSEP" "${ARGS[@]}" "${FILE[@]}" | \
            "$FEXTRACTOR" ${FEX_OPTS[*]} -r "$XER_FILE" -w "$OUT_FILE"
    else
        $AWK ${OPTS[*]} -F"$FS" -v OFS="$OFS" -v __HDRSEP__="$HDRSEP" "${ARGS[@]}" "${FILE[@]}" | \
            "$FEXTRACTOR" ${FEX_OPTS[*]} -r "$XER_FILE" -w - | $WIRESHARK -k -i -
    fi
fi
