#!/bin/bash

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

usage() {
    printf "Usage:\n"
    printf "    tawk [OPTION...] 'program' file_flows.txt\n\n"
    printf "Optional arguments:\n"
    printf "    -l[=n], --list[=n]  List column names and numbers\n"
    printf "    -f[=n], --func[=n]  List available functions\n"
    printf "    -d fname            Display function 'fname' documentation\n"
    printf "    -n                  Load nfdump functions\n"
    printf "    -e                  Load examples\n"
    printf "    -c                  Output command line as a comment\n"
    printf "    -t                  Do not validate column names\n"
    printf "    -?, -h, --help      Show help otions 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_arg() {
    if [ -n "$2" ] && [ "${2:0:1}" != "-" ]; then
        return 0
    else
        _printerr "Option '$1' requires an argument"
        _abort_with_help
    fi
}

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

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

_check_dependencies_linux() {
    local deps="coreutils gawk sed"
    local pgrmname pgrmcmd
    type gawk readlink sed &> /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
    }

    local gver="$(gawk --version | awk '{print $3; exit}')"
    if [[ $gver < 4.1 ]]; then
        _printerr "Minimum gawk version required is 4.1, found '$gver'"
        exit 1
    fi

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

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

# 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

list_names() {
    local cnt=1
    local d="$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"
    local funcs=("$TAWKHOME/funcs/*[^\.load]")
    [ $NFDUMP ] && funcs+=("$TAWKHOME/t2nfdump/*[\.load]")
    [ $EXAMPLES ] && funcs+=("$TAWKHOME/examples/*[^\.load]")
    [ -f "$TAWKHOME/t2custom.awk" ] && funcs+=($(grep -h ^function "$TAWKHOME/t2custom.awk" | $SED 's/function[[:space:]]\+\([[:alnum:]]\+\)(.*/\1/'))
    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 -e "\$.*" <<< "$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 ")" }')"
    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
}

VALIDATE_NAMES=1
FILE="${@:$#}"
ARGS=()

while [ $# -gt 0 ]; do
    case $1 in
        -c|--comment) COMMENT=1;;
        -t) unset VALIDATE_NAMES;;
        -e|--examples) EXAMPLES=1;;
        -n|--nfdump) NFDUMP=1;;
        -l|-l=*|--list|--list=*) LIST_NAMES="${1#*=}";;
        -f|-f=*|--func|--func=*) LIST_FUNCS="${1#*=}";;
        -d|--doc)
            _validate_arg "$1" "$2"
            DOC="$2"
            ;;
        -\?|-h|--help)
            usage
            exit 0
            ;;
        *)
            ARGS+=("$1")
            ;;
    esac
    shift
done

if [ -n "$DOC" ]; then
    doc "$DOC"
    exit 0
fi

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

if [ ! -f "$FILE" ] && readlink /proc/$$/fd/0 | grep -q "^pipe:"; then
    # Reading from stdin: no access to column names
    unset FILE
    if [ $LIST_NAMES ]; then
        _printerr "No access to column names when reading from stdin"
        _abort_with_help
    fi
elif [ ! -f "$FILE" ]; then
    _printerr "Input file is required"
    _abort_with_help
else
    names=($($AWK -F'\t' '$1 ~ /^%[[:space:]]*[[:alpha:]][[:alnum:]_]*$/ { print; exit }' "$FILE" | $SED 's/^%//'))
    if [ -z "$names" ] && { [ $LIST_NAMES ] || [ $VALIDATE_NAMES ]; }; then
        _printerr "Column names not found"
        exit 1
    fi

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

    if [ $VALIDATE_NAMES ]; then
        validate_names
    fi

    if [ -n "$ZSH_VERSION" ]; then
        ARGS[${#ARGS[@]}]=() # remove filename
    else
        unset ARGS[${#ARGS[@]}-1] # remove filename
    fi
fi

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

# Prepare mapping between columns name and number
CNT=1
STR=()
for i in ${names[@]}; do
    STR+=(-v $i=$CNT)
    CNT=$((CNT+1))
done

# 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.awk" ]; then
    OPTS+=(-i "$TAWKHOME/t2custom.awk")
fi

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

export AWKPATH
$AWK ${OPTS[*]} -F'\t' -v OFS='\t' ${STR[*]} "${ARGS[@]}" "$FILE"
