# Copyright (c) 2017 albaldi
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# See here for updates: https://github.com/megous/megatools/issues/368

# Completes both "megatools <command> ..." and the compatibility symlinks
# (megals, megadl, ...). Option lists are from "megatools <command> --help".
# Remote paths are completed by running "megatools ls" with the login options
# given on the command line (or from ~/.megarc); it never asks for a password.

# a word as the shell will pass it: without the quotes and backslashes
_megatools_dequote()
{
        local w="$1"
        case "$w" in
                \'*)   w="${w#\'}"; w="${w%\'}" ;;
                \"*)   w="${w#\"}"; w="${w%\"}" ;;
                *)      w="${w//\\/}" ;;
        esac
        printf '%s' "$w"
}

# the megatools binary being completed (./build/megatools, megals, ...)
_megatools_bin()
{
        local bin="${COMP_WORDS[0]/#\~/$HOME}"
        if [[ "${bin##*/}" == megatools ]] ; then
                printf '%s' "$bin"
        elif [[ "$bin" == */* ]] ; then
                printf '%s' "${bin%/*}/megatools"
        else
                printf megatools
        fi
}

# local files (-d: directories), also without the bash-completion package
_megatools_files()
{
        if declare -F _filedir >/dev/null ; then
                _filedir "$@"
        elif [[ "$1" == -d ]] ; then
                mapfile -t COMPREPLY < <( compgen -d -- "$cur" )
        else
                mapfile -t COMPREPLY < <( compgen -f -- "$cur" )
        fi
}

_megatools_remotepath()
{
        local cur dir i w v
        local -a flags names
        # $1: the word being completed
        cur="$(_megatools_dequote "$1")"

        # the top level: /Root, /Trash, /Shared (or a @<handle> path)
        if [[ "$cur" != /*/* && "$cur" != @*/* ]] ; then
                [[ "$cur" == @* ]] && return 0
                mapfile -t COMPREPLY < <( compgen -W "/Root /Trash /Shared" -- "$cur" )
                return 0
        fi
        dir="${cur%/*}"

        # pass the options that select the account and the connection on to
        # "megatools ls" (not --2fa-code, a code can be used only once)
        for (( i = 1; i < COMP_CWORD; i++ )); do
                w="${COMP_WORDS[i]}"
                case "$w" in
                        --config|--proxy|--username|-u|--password|-p|--2fa-secret|--netif|--ip-proto)
                                (( i + 1 < COMP_CWORD )) || continue
                                v="${COMP_WORDS[i+1]}"
                                # --option=value is split at the =
                                if [[ "$v" == "=" ]] ; then
                                        (( i + 2 < COMP_CWORD )) || continue
                                        v="${COMP_WORDS[i+2]}"
                                fi
                                flags+=("$w" "$(_megatools_dequote "$v")")
                                ;;
                        --ignore-config-file)
                                flags+=("$w")
                                ;;
                esac
        done

        # the names in the folder, joined to the typed folder path
        mapfile -t -d '' names < <( "$(_megatools_bin)" ls --names --print0 --no-ask-password "${flags[@]}" "$dir" 2>/dev/null )
        for w in "${names[@]}"; do
                [[ "$dir/$w" == "$cur"* ]] && COMPREPLY+=("$dir/$w")
        done
}

_megatools()
{
    local cur prev cmd
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    # --option=value is split into "--option" "=" "value"
    if [[ "${cur}" == "=" ]] ; then
            cur=""
    elif [[ "${prev}" == "=" && ${COMP_CWORD} -ge 2 ]] ; then
            prev="${COMP_WORDS[COMP_CWORD-2]}"
    fi

    case "${COMP_WORDS[0]##*/}" in
            megatools)
                    if [[ ${COMP_CWORD} -eq 1 ]] ; then
                            mapfile -t COMPREPLY < <( compgen -W "2fa copy df dl export get ls mkdir passwd put reg rm test --help --version" -- "${cur}" )
                            return 0
                    fi
                    cmd="${COMP_WORDS[1]}"
                    ;;
            mega*)
                    cmd="${COMP_WORDS[0]##*/}"
                    cmd="${cmd#mega}"
                    ;;
            *)
                    return 0
                    ;;
    esac

    local common="-h --help --help-all --config --ignore-config-file --debug --version --limit-speed --proxy --netif --ip-proto"
    local auth="-u --username -p --password --no-ask-password --2fa-code --2fa-secret --reload"

    local opts
    case "${cmd}" in
            2fa)    opts="$common $auth --setup --enable --disable --scripted" ;;
            copy)   opts="$common $auth --enable-previews --disable-previews --disable-resume -r --remote -l --local -d --download --no-progress --no-follow -n --dryrun" ;;
            df)     opts="$common $auth -h --human --mb --gb --total --used --free" ;;
            dl)     opts="$common $auth --disable-resume --path --no-progress --print-names --choose-files --list" ;;
            export) opts="$common $auth --remove" ;;
            get)    opts="$common $auth --disable-resume --path --no-progress" ;;
            ls)     opts="$common $auth -n --names -R --recursive -l --long --header -h --human -0 --print0 -e --export" ;;
            mkdir)  opts="$common $auth" ;;
            passwd) opts="$common $auth --new-password" ;;
            put)    opts="$common $auth --enable-previews --disable-previews --path --no-progress --overwrite" ;;
            reg)    opts="$common -n --name -e --email -p --password --register --verify --scripted" ;;
            rm)     opts="$common $auth" ;;
            test)   opts="$common $auth -f --file -d --folder" ;;
            *)      return 0 ;;
    esac

    # option values
    case "${prev}" in
            --config)
                    _megatools_files
                    return 0
                    ;;
            --local|-l)
                    [[ "${cmd}" == copy ]] && { _megatools_files -d; return 0; }
                    ;;
            --remote|-r)
                    [[ "${cmd}" == copy ]] && { _megatools_remotepath "${cur}"; return 0; }
                    ;;
            --path)
                    if [[ "${cmd}" == put ]] ; then
                            _megatools_remotepath "${cur}"
                    else
                            _megatools_files
                    fi
                    return 0
                    ;;
            --debug)
                    # a comma separated list: complete its last word
                    local done=""
                    [[ "${cur}" == *,* ]] && done="${cur%,*},"
                    mapfile -t COMPREPLY < <( compgen -P "${done}" -W "api fs cache http tman" -- "${cur##*,}" )
                    return 0
                    ;;
            --ip-proto)
                    mapfile -t COMPREPLY < <( compgen -W "v4 v6 any" -- "${cur}" )
                    return 0
                    ;;
            --username|-u|--password|-p|--proxy|--netif|--limit-speed|--2fa-code|--2fa-secret|--new-password|--name|--email|--enable|--disable)
                    return 0
                    ;;
            -n|-e)
                    # reg --name, --email; other commands use them as flags
                    [[ "${cmd}" == reg ]] && return 0
                    ;;
    esac

    if [[ ${cur} == -* ]] ; then
            mapfile -t COMPREPLY < <( compgen -W "${opts}" -- "${cur}" )
            return 0
    fi

    # arguments
    case "${cmd}" in
            mkdir|rm|get|ls|test|export)
                    _megatools_remotepath "${cur}"
                    ;;
            put)
                    _megatools_files
                    ;;
    esac
}
# -o filenames: _megatools_remotepath results get quoted/escaped like file names
complete -o filenames -F _megatools megatools megacopy megadl megals megaput megarm megadf megaget megamkdir megareg megatest megaexport mega2fa megapasswd

# /* vim: set filetype=sh ts=8: */
