#!/bin/bash
#
# Aliases for Tranalyzer (tested with Bash and ZSH)
#
# Known issues:
#   [ZSH]
#       - alias lsx is already defined
#         fix: type 'unalias lsx' before sourcing this file
#
# To activate these aliases, append the following lines to ~/.bashrc or
# ~/.bash_aliases (make sure to replace $T2HOME with the actual path, e.g.,
# $HOME/int_tranalyzer/trunk):
#
#      if [ -f "$T2HOME/scripts/t2_aliases" ]; then
#          . "$T2HOME/scripts/t2_aliases"             # Note the leading '.'
#      fi
#
# TODO
#   - Improve ZSH/Bash completion
#       - tawk: ignore '$' when completing variable names
#       - describe options

# Private functions
_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
}

# To force deactivation of the completion, replace HAS_COMPLETION with _HAS_COMPLETION
if hash complete 2> /dev/null || type compdef &> /dev/null; then
    HAS_COMPLETION=1
else
    _printwrn "No valid completion program found."
    _printinf "Try installing 'bash-completion' with your package utility"
fi

# Required programs
if [ "$(uname)" = "Darwin" ]; then
    type gawk greadlink gsed &> /dev/null || {
        deps="coreutils gawk gnu-sed"
        _printerr "t2_aliases: missing dependencies: $deps"
        _printinf "You may use homebrew to install them: brew install $deps"
        return 1
    }
    if [ -n "$ZSH_VERSION" ] && [[ $(zsh --version | awk '{print $2}') < 5.2 ]]; then
        _printwrn "Your zsh version does not support tab completion"
        unset HAS_COMPLETION
    fi
    AWK="$(which gawk)"
    READLINK="$(which greadlink)"
    SED="$(which gsed)"
    OPEN="open"
else
    deps="coreutils gawk sed"
    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 "t2_aliases: missing dependencies: $deps"
        _printinf "You may use $pgrmname to install them$pgrmcmd"
        return 1
    }
    GVER="$(gawk --version | awk '{print $3; exit}')"
    if [[ $GVER < 4.1 ]]; then
        _printerr "t2_aliases: minimum gawk version required is 4.1, found '$GVER'"
        return 1
    fi
    AWK="$(which gawk)"
    READLINK="$(which readlink)"
    SED="$(which sed)"
    OPEN="$(which xdg-open)"
fi

# Check for completion
if [ -z "$ZSH_VERSION" ] && [ -n "$HAS_COMPLETION" ]; then
    if [ ! -f "/usr/share/bash-completion/bash_completion" ] ||
       [ -z "$(grep "^_init_completion()" /usr/share/bash-completion/bash_completion 2> /dev/null)" ]
    then
        _printwrn "Deactivating completion as your bash-completion version does not provide the '_init_completion()' function."
        unset HAS_COMPLETION
    fi
fi

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

# Tranalyzer
alias t2="$T2HOME/tranalyzer2/src/tranalyzer"
alias gt2="gdb --args $T2HOME/tranalyzer2/src/tranalyzer"
alias tranalyzer="$T2HOME/tranalyzer2/src/tranalyzer"

# Bash/ZSH completion for t2, gt2 and tranalyzer
if [ $HAS_COMPLETION ]; then
    _t2() {
        #compdef t2 gt2 tranalyzer
        if type compdef &> /dev/null; then
            local opts=(
                '(-r -R -D)'{-i,-i}'[Listen on interface]:interface:_net_interfaces'
                '(-i -R -D)'{-r,-r}'[Read packets from PCAP file]:file:_files'
                '(-i -r -D)'{-R,-R}'[Process every PCAP file listed in FILE]:file:_files'
                '(-i -r -R)'{-D,-D}'[Process every PCAP whose name matches EXPR]:_files'
                '(-w -W)'{-w,-w}'[Apprend PREFIX to any output file produced]:output prefix:_files'
                '(-w -W)'{-W,-W}'[Like -w, but fragment flow files according to SIZE]:output prefix:_files'
                '-l[Print end report in PREFIX_log.txt instead of stdout]'
                '-b[Use plugin loading list FILE]:file:_files'
                '-s[Packet forensics mode]'
                '-F[Read BPF filter from file]:file:_files'
                '-p[Load plugins from path PATH instead of ~/.tranalyzer/plugins]:plugin folder:_files -/'
                '-f[hashfactor]:Multiplication factor for hash table (int):'
                '-x[Sensor ID]:sensor ID (int):'
                '(- 1 *)'{-v,-v}'[Show the version of the program and exit]'
                '(- 1 *)'{-h,--help}'[Show help options and exit]'
            )
            if [[ "$OSTYPE" != darwin* ]]; then
                opts+=('-c[Bind tranalyzer to one core]:CPU core number (int):')
            fi
            _arguments -s -S "${opts[@]}"
        else # BASH
            local cur prev words cword
            _init_completion || return
            case $prev in
                -i)
                    # active interfaces only
                    _available_interfaces -a
                    return
                    ;;
                -b|-e|-r|-R|-D|-F|-w|-W)
                    _filedir
                    return
                    ;;
                -p)
                    _filedir -d
                    return
                    ;;
                -c)
                    COMPREPLY=($(compgen -W "$(seq 0 $(_ncpus))" -- "$cur"))
                    return
                    ;;
            esac
            local args=(-i -r -R -D -e -w -W -l -b -s -f -F -p -x -v -h --help)
            if [[ "$OSTYPE" != darwin* ]]; then
                args+=(-c)
            fi
            COMPREPLY=($(compgen -W "${args[*]}" -- "$cur"))
        fi
    }
    if type compdef &> /dev/null; then
        compdef _t2 t2 gt2 tranalyzer
    else
        complete -F _t2 t2 gt2 tranalyzer
    fi
fi

alias tran="cd $T2HOME"
alias .tran="cd $HOME/.tranalyzer/plugins/"

# Access every plugin folder by its name,
# e.g., tcpFlags instead of cd $T2HOME/tcpFlags
for i in $T2HOME/*; do
    b=$(basename $i)
    if [ -d $i ] && [ "$b" != "doc" ]; then
        alias $b="cd $i"
    fi
done

alias awkf="$AWK -F'\t' -v OFS='\t'"
alias sortu="sort | uniq -c | sort -rn"

# Make some scripts globally accessible
alias protStat="$T2HOME/protoStats/protStat"
alias rrdmonitor="$T2HOME/scripts/rrdmonitor"
alias rrdplot="$T2HOME/scripts/rrdplot"
alias t2conf="$T2HOME/scripts/t2conf/t2conf"
alias t2dmon="$T2HOME/scripts/t2dmon"
alias t2fm="$T2HOME/scripts/t2fm"
alias t2plot="$T2HOME/scripts/t2plot"
alias tawk="$T2HOME/scripts/tawk/tawk"

# Bash/ZSH completion for various aliases
if [ $HAS_COMPLETION ]; then
    # Bash/ZSH completion for rrdplot
    _rrdplot() {
        #compdef rrdplot
        local cur prev
        if type compdef &> /dev/null; then
            cur="${words[CURRENT]}"
            [ $CURRENT -gt 2 ] && prev=${words[CURRENT-1]}
        else
            local words cword
            _init_completion || return
        fi
        if [[ "$cur" == -* ]]; then
            if type compdef &> /dev/null; then
                _arguments --
            else
                COMPREPLY=($(compgen -W "$(_parse_help "$T2HOME/scripts/rrdplot")" -- "$cur"))
            fi
        elif [ "$prev" = "-d" ] || [ "$prev" = "-p" ]; then
            if type compdef &> /dev/null; then
                _files
            else
                _filedir
            fi
        else
            local db="monitoring.rrd"
            local buf="${COMP_LINE:-$BUFFER}"
            if [[ "$buf" = *[[:space:]]-d[[:space:]]*.rrd* ]]; then
                db="$(echo "$buf" | $SED 's/.*-d\s\+//')"
                db="$(echo "$db" | $SED 's/\.rrd.*/.rrd/')"
                # replace ~ with $HOME
                db="$(eval "echo \"$db\" | $SED 's|^~|$HOME|'")"
            fi
            if [ -f "$db" ]; then
                local vars=($(rrdtool info "$db" | grep "ds\[" | cut -d'[' -f2 | cut -d']' -f1 | uniq))
                if type compdef &> /dev/null; then
                    compadd "${vars[@]}"
                else
                    COMPREPLY=($(compgen -W "${vars[*]}" -- "$cur"))
                fi
            fi
        fi
    }
    if type compdef &> /dev/null; then
        compdef _rrdplot rrdplot
    else
        complete -F _rrdplot rrdplot
    fi
    # Bash/ZSH completion for t2conf
    _t2conf() {
        #compdef t2conf
        local cur prev
        if type compdef &> /dev/null; then
            [ $CURRENT -gt 2 ] && prev="${words[CURRENT-1]}"
        else
            local words cword
            _init_completion || return
        fi
        case "$prev" in
            -t|-p)
                if type compdef &> /dev/null; then
                    _files -/
                else
                    _filedir -d
                fi
                return
                ;;
            -s|-r|--patch|--rpatch)
                if type compdef &> /dev/null; then
                    _files
                else
                    _filedir
                fi
                return
                ;;
        esac
        local plugins=()
        for i in "$T2HOME"/*; do
            local b=$(basename "$i")
            if [ -d "$i" ] && [ "$b" != "doc" ] && [ "$b" != "t2PSkel" ] && [ "$b" != "scripts" ] && [ "$b" != "utils" ]; then
                plugins+=($b)
            fi
        done
        if [[ "${words[CURRENT]}" == -* ]]; then
            _arguments --
        elif [[ "$cur" = -* ]]; then
            COMPREPLY=($(compgen -W "$(_parse_help "$T2HOME/scripts/t2conf/t2conf")" -- "$cur"))
        elif type compdef &> /dev/null; then
            compadd "${plugins[@]}"
        else
            COMPREPLY=($(compgen -W "${plugins[*]}" -- "$cur"))
        fi
    }
    if type compdef &> /dev/null; then
        compdef _t2conf t2conf
    else
        complete -F _t2conf t2conf
    fi
    # Bash/ZSH completion for t2dmon
    _t2dmon() {
        #compdef t2dmon
        if type compdef &> /dev/null; then
            if [[ "${words[CURRENT]}" == -* ]]; then
                _arguments --
            else
                _files -/
            fi
        else
            local cur prev words cword
            _init_completion || return
            if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "$(_parse_help "$T2HOME/scripts/t2dmon")" -- "$cur"))
            else
                _filedir -d
            fi
        fi
    }
    if type compdef &> /dev/null; then
        compdef _t2dmon t2dmon
    else
        complete -F _t2dmon t2dmon
    fi
    # Bash/ZSH completion for t2plot
    _t2plot() {
        #compdef t2plot
        if type compdef &> /dev/null; then
            if [[ "${words[CURRENT]}" == -* ]]; then
                _arguments --
            else
                _files
            fi
        else
            local cur prev words cword
            _init_completion || return
            if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "$(_parse_help "$T2HOME/scripts/t2plot")" -- "$cur"))
            else
                _filedir
            fi
        fi
    }
    if type compdef &> /dev/null; then
        compdef _t2plot t2plot
    else
        complete -F _t2plot t2plot
    fi
fi

# Bash/ZSH completion for tawk
if [ $HAS_COMPLETION ]; then
    _tawk() {
        #compdef tawk
        local cur prev
        if type compdef &> /dev/null; then
            [ $CURRENT -gt 2 ] && prev="${words[CURRENT-1]}"
        else
            local words cword
            _init_completion || return
        fi
        case "$prev" in
            -d)
                local opts=(all examples funcs t2nfdump)
                opts+=($(ls $T2HOME/scripts/tawk/{examples,funcs,t2nfdump}/* | awk -F'/' '{print $NF}' | grep -v \.load$))
                if type compdef &> /dev/null; then
                    compadd "${opts[@]}"
                else
                    COMPREPLY=($(compgen -W "${opts[*]}" -- "$cur"))
                fi
                return
                ;;
        esac
        local file="$(echo "${COMP_LINE:-$BUFFER}" | awk '{print $NF}')"
        if [ -f "$file" ]; then
            # functions from tawk and variable names from 'file'
            local opts=($(ls $T2HOME/scripts/tawk/{examples,funcs,t2nfdump}/* | awk -F'/' '{print $NF}' | grep -v \.load$))
            opts+=($($AWK -F'\t' '$1 ~ /^%[[:space:]]*[[:alpha:]][[:alnum:]_]*$/ { sub(/^%[[:space:]]*/, ""); for (i = 1; i <= NF; i++) { printf " %s", $i; } exit }' "$file"))
            if type compdef &> /dev/null; then
                compadd "${opts[@]}"
            else
                COMPREPLY=($(compgen -W "${opts[*]}" -- "$cur"))
            fi
        elif type compdef &> /dev/null; then
            _files
        else
            _filedir
        fi
    }
    if type compdef &> /dev/null; then
        compdef _tawk tawk
    else
        complete -F _tawk tawk
    fi
fi

tcol() {
    local ubuntu
    if hash apt-get 2> /dev/null; then
        ubuntu="-n -e"
    fi

    if [ $# -eq 0 ]; then
        eval "column -t -s $'\t' $ubuntu | less -S"
    else
        eval "column -t -s $'\t' $ubuntu \"$@\" | less -S"
    fi
}

lsx() {
    local WIDTH=40
    if [ $# -gt 0 ] && [ -z "$(echo "$1" | $SED 's/^[0-9]\+$//')" ]; then
        WIDTH=$1
        shift
    fi
    less -RSx${WIDTH} "$@"
}

t2build() {
    local olddir=`pwd`
    local opts=()
    local gopts=()
    local plugins=()
    while [ $# -gt 0 ]; do
        case "$1" in
            -a|--all|-K|--package-all|-l|--list|-R|--rebuild|-e|--empty)
                gopts+=("$1")
                ;;
            -r|--configure|-d|--debug|-c|--clean|-i|--install|-k|--package|-f|--force|-u|--unload|-L|--lazy)
                opts+=("$1")
                ;;
            # missing required arguments are handled by autogen.sh
            -b|--build|-I|--ignore)
                gopts+=("$1")
                if [ -n "$2" ] && [ "${2:0:1}" != "-" ]; then
                    shift
                    # get the absolute path
                    if [[ "$1" = /* ]]; then
                        gopts+=("$1")
                    else
                        gopts+=("$PWD/$1")
                    fi
                fi
                ;;
            -p|--plugin-dir)
                opts+=("$1")
                if [ -n "$2" ] && [ "${2:0:1}" != "-" ]; then
                    shift
                    # get the absolute path
                    if [[ "$1" = /* ]]; then
                        opts+=("$1")
                    else
                        opts+=("$PWD/$1")
                    fi
                fi
                ;;
            -o)
                opts+=("$1")
                if [ -n "$2" ] && [ "${2:0:1}" != "-" ]; then
                    shift
                    opts+=("$1")
                fi
                ;;
            -\?|-h|--help)
                echo "Usage:"
                echo "    t2build [OPTION...] [plugin...]"
                echo
                echo "Optional arguments:"
                echo "    -a            build all plugins (recursive)"
                echo "    -b [file]     build plugins listed in 'plugins.build' or 'file'"
                echo "    -I file       ignore plugins listed in 'file' (used with -a option)"
                echo "    -R            rebuild Tranalyzer and all the plugins in the plugin folder"
                echo "    plugin        a list of valid plugin names (use TAB for completion)"
                echo
                echo "    -c            execute make clean and remove automatically generated files"
                echo "    -d            compile in debug and profiling mode"
                echo "    -L            lazy mode (run make all instead of make clean all)"
                echo "    -r            force rebuild of makefiles"
                echo "    -u            unload/remove the plugin from the plugin folder"
                echo "    -e            empty the plugin folder and exit"
                echo "    -k            create one compressed archive per plugin"
                echo "    -K            create one compressed archive with the requested plugins"
                echo
                echo "    -f            force the copy of extra files"
                echo
                echo "    -i            install Tranalyzer binary in /usr/local/bin"
                echo "    -p dir        plugin install directory (default: ~/.tranalyzer/plugins)"
                echo
                echo "    -o level      gcc optimization level"
                echo
                echo "    -h, --help    show help options and exit"
                return
                ;;
            -*)
                _printerr "Unknown option '$1'"
                return 1
                ;;
            *)
                if [ ! -d "$T2HOME/$1" ]; then
                    _printerr "Plugin '$1' not found"
                    return 1
                elif [ ! -f "$T2HOME/$1/autogen.sh" ]; then
                    _printerr "$1 is not a valid Tranalyzer plugin"
                    return 1
                fi
                plugins+=($1)
                ;;
        esac
        shift
    done
    cd "$T2HOME"
    local ret=0;
    if [ -z "$plugins" ]; then
        if [ ! -f "$T2HOME/autogen.sh" ]; then
            _printerr "$T2HOME is not a valid Tranalyzer directory"
        else
            ./autogen.sh "${opts[@]}" "${gopts[@]}"
            ret=$?
        fi
    else
        if [ -n "$gopts" ]; then
            _printwrn "\nIgnoring the following global options: $($SED 's/^\s\+//' <<< "$gopts")\n"
        fi
        for i in ${plugins[@]}; do
            cd "$i"
            ./autogen.sh "${opts[@]}"
            let "ret|=$?"
            cd ..
        done
    fi
    [ -d "$olddir" ] && cd "$olddir"
    return $ret
}

# Bash/ZSH completion for t2build
if [ $HAS_COMPLETION ]; then
    _t2build() {
        #compdef t2build
        local cur prev
        if type compdef &> /dev/null; then
            cur="${words[CURRENT]}"
            [ $CURRENT -gt 2 ] && prev=${words[CURRENT-1]}
        else
            local words cword
            _init_completion || return
        fi
        local args=(-a --all -b --build -i --install -R --rebuild -I --ignore
                    -k --package -r --configure -d --debug -c --clean -f --force
                    -u --unload -o -p --plugin-dir -K --package-all -l --list
                    -e --empty -\? -h --help)
        case $prev in
            -p)
                if type compdef &> /dev/null; then
                    _files -/
                else
                    _filedir -d
                fi
                return
                ;;
            -I)
                if type compdef &> /dev/null; then
                    _files
                else
                    _filedir
                fi
                return
                ;;
        esac
        if [[ "$cur" == -* ]]; then
            if type compdef &> /dev/null; then
                _arguments --
            else
                COMPREPLY=($(compgen -W "${args[*]}" -- "$cur"))
            fi
            return
        fi
        local plugins=()
        for i in "$T2HOME"/*; do
            local b=$(basename "$i")
            if [ -d "$i" ] && [ "$b" != "doc" ] && [ "$b" != "t2PSkel" ] && [ "$b" != "scripts" ] && [ "$b" != "utils" ]; then
                plugins+=($b)
            fi
        done
        if [ "$prev" = "-b" ]; then
            if type compdef &> /dev/null; then
                compadd "${plugins[@]}"
            else
                compopt -o nospace
                COMPREPLY=($(compgen -f -W "${plugins[*]}" -- "$cur"))
            fi
        elif type compdef &> /dev/null; then
            compadd "${plugins[@]}"
        else
            COMPREPLY=($(compgen -W "${plugins[*]}" -- "$cur"))
        fi
    }
    if type compdef &> /dev/null; then
        compdef _t2build t2build
    else
        complete -F _t2build t2build
    fi
fi

t2stat() {
    local cmd
    if [ -n "$1" ]; then
        cmd="watch -n $1"
    fi
    local pid="$(pidof tranalyzer)"
    if [ -z "$pid" ]; then
        echo "No running instance of Tranalyzer found"
    else
        $cmd kill -USR1 "$pid"
    fi
}

t2edit() {
    local editor="${EDITOR:-vim}"
    if [ -z "$1" ] || [ ! -f "$T2HOME/$1" ]; then
        echo "Usage: t2edit <file>"
        return
    fi
    "$editor" "$T2HOME/$1"
}

# Bash/ZSH completion for t2edit
if hash complete 2> /dev/null || type compdef &> /dev/null; then
    _t2edit() {
        #compdef t2edit
        local opts=()
        local olddir=`pwd`
        cd "$T2HOME"
        for i in */src/*.[ch]; do
            local b=$(dirname "$i")
            b=$(dirname "$b") # plugin name
            if [ "$b" != "t2PSkel" ]; then
                opts+=("$i")
            fi
        done
        if type compdef &> /dev/null; then
            compadd "${opts[@]}"
        else
            local cur="${COMP_WORDS[COMP_CWORD]}"
            COMPREPLY=($(compgen -W "${opts[*]}" -- "$cur"))
        fi
        cd "$olddir"
    }
    if type compdef &> /dev/null; then
        compdef _t2edit t2edit
    else
        complete -F _t2edit t2edit
    fi
fi

t2doc() {
    local cmd="${OPEN}"
    : ${cmd:="$(which evince)"}
    if [ -z "$cmd" ]; then
        _printerr "No PDF viewer found"
        return
    fi
    if [ -z "$1" ]; then
        if [ ! -f "$T2HOME/doc/documentation.pdf" ]; then
            printf "Tranalyzer documentation does not exist... build it (Y/n)? "
            read ans
            case $ans in
                N|n) return
            esac
            make -C "$T2HOME/doc/" || {
                _printerr "Failed to build Tranalyzer documentation"
                return
            }
        fi
        $cmd "$T2HOME/doc/documentation.pdf" 2>/dev/null &
    elif [ "$1" = "tawk" ]; then
        $cmd "$T2HOME/scripts/$1/doc/$1.pdf" 2>/dev/null &
    elif [ ! -d "$T2HOME/$1" ]; then
        _printerr "Plugin '$1' not found"
    elif [ ! -f "$T2HOME/$1/doc/$1.pdf" ]; then
        printf "Documentation for plugin '$1' does not exist... build it (Y/n)? "
        read ans
        case $ans in
            N|n) return
        esac
        make -C "$T2HOME/$1/doc/" || {
            _printerr "Failed to build '$1' documentation"
            return
        }
        $cmd "$T2HOME/$1/doc/$1.pdf" 2>/dev/null &
    else
        $cmd "$T2HOME/$1/doc/$1.pdf" 2>/dev/null &
    fi
}

# Bash/ZSH completion for t2doc
if [ $HAS_COMPLETION ]; then
    _t2doc() {
        #compdef t2doc
        local plugins=(tawk)
        for i in "$T2HOME"/*; do
            local b=$(basename "$i")
            if [ -d "$i" ] && [ "$b" != "doc" ] && [ "$b" != "t2PSkel" ] && [ "$b" != "utils" ]; then
                plugins+=($b)
            fi
        done
        if type compdef &> /dev/null; then
            compadd "${plugins[@]}"
        else
            local cur="${COMP_WORDS[COMP_CWORD]}"
            COMPREPLY=($(compgen -W "${plugins[*]}" -- "$cur"))
        fi
    }
    if type compdef &> /dev/null; then
        compdef _t2doc t2doc
    else
        complete -F _t2doc t2doc
    fi
fi

# fextractor
if [ -d "$T2HOME/findexer/fextractor" ]; then
    alias fextractor="$T2HOME/findexer/fextractor/fextractor"
    # Bash/ZSH completion for fextractor
    if [ $HAS_COMPLETION ]; then
        _fextractor() {
            #compdef fextractor
            local cur prev
            if type compdef &> /dev/null; then
                local opts=(
                    '(-R)'{-r,-r}'[Read offsets from XER file]:file:_files'
                    '(-r)'{-R,-R}'[Read offsets from multiple XER files]:file:_files'
                    '(-j)'{-i,-i}'[Read flow indexes from FILE]:file:_files'
                    '-w[Write packets to PCAP FILE]:file:_files'
                    '-s[Skip the first N PCAPs]:number of PCAP to skip (int):'
                    '-f[Overwrite OUTPUTFILE if it already exists]'
                    '-n[Print oldest PCAP still available, its first packet timestamp and exit]'
                    '-p[Search PCAPs in DIR]:directory:_files -/'
                    '(- 1 *)'{-h,-h}'[Show help options and exit]'
                )
                _arguments -s -S "${opts[@]}"
            else
                local cur prev words cword
                _init_completion || return
                case $prev in
                    -r|-R|-i|-j|-w)
                        _filedir
                        return
                        ;;
                    -p)
                        _filedir -d
                        return
                        ;;
                esac
                if [[ "$cur" == -* ]]; then
                    COMPREPLY=($(compgen -W "$(_parse_help "$T2HOME/findexer/fextractor/fextractor" -h)" -- "$cur"))
                fi
            fi
        }
    fi
    if type compdef &> /dev/null; then
        compdef _fextractor fextractor
    else
        complete -F _fextractor fextractor
    fi
fi
