# Copyright (c) 2021, Oracle and/or its affiliates.  All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.

UPDATED="2021-04-26"

# This supports bash and zsh autocomplete for the o command.
# The same autocomplete works for "oci" as well.
#
# It uses the o's oci_commands file to get a list of commands, subcommands
# and parameters. Completion options are found by
# perl-ing oci_commands, which makes it really FAST and effective.
#
# REQUIRES: $HOME/.oci/oci_commands file, a text file listing
# of oci commands and parameters (courtesy of Project o)
OCI_COMMANDS=$HOME/.oci/oci_commands
[ ! -e $OCI_COMMANDS ] && OCI_COMMANDS=`which oci`_commands

# zsh setup for MacOS
# autoload -U +X bashcompinit && bashcompinit
# autoload -U +X compinit && compinit

# zsh setup for Linux
# autoload bashcompinit
# bashcompinit

# call function _o_completion for o or oci when [tab] is pressed
complete -F _o_completion o
complete -F _o_completion oci

# log useful for debugging; otherwise it's hard to see what's going on
pdate() { echo -e "import datetime as dt\nprint(dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])"| python; }
log() { echo $(pdate) $@ >> log.txt ;}

# This function called on [tab] press
_o_completion() {
    export word="${COMP_WORDS[COMP_CWORD]}"    # possible incomplete last word
    IN="${COMP_WORDS[@]}"
    IN=${IN/#o/oci}
    IN=${IN/#ocici/oci}
    # log A .${IN}. word .${word}.
    export IN
    if [ "${IN}" = "${IN%% -*}" ]
    then
        if [ "$word" != "" ]; then
            clist=$(perl -e 'my %c; if ($ENV{IN} =~ /(.*) (.*)/) { ($p1,$p2)=($1,$2) } # noqa: E999
                         while (<>) { $c{$1}=1 if /^$p1 ($p2\S*) /;}
                         $,="\n"; print sort keys %c;' $OCI_COMMANDS)
            # log B $clist
        else
            IN="${IN%% } "
            clist=$(perl -e 'my %c; while (<>) { $c{$1}=1 if /^$ENV{IN}([^-]\S+) /;}
                             $,="\n"; print sort keys %c;' $OCI_COMMANDS)
            # log C $clist
            [ "$clist" = "" ] && clist=$(grep "$IN" $OCI_COMMANDS |
                perl -pe 's/.*? -/-/; s/\+ //; s/ [^-]\S+//g; @c{split /\s+/}=(); $,="\n"; print sort keys %c')
            # log D $clist
        fi
        COMPREPLY=($(compgen -W "$clist" -- "$word"));
    else
        clist=$(grep "${IN%% -*}" $OCI_COMMANDS |
            perl -ne 's/.*? -/-/; s/\+ //; s/ [^-]\S+//g; @c{split /\s+/}=(); $,="\n"; print sort keys %c')
        # log E $clist
        for i in ${COMP_WORDS[@]}; do      # remove already used params from list
            [ "${i%%-*}" = "" ] && [ "$i" != "$word" ] && clist=${clist/$i/}
        done
        COMPREPLY=($(compgen -W "$clist" -- "$word"));
    fi
    # log R ${COMPREPLY[@]}
}
