#!/bin/bash -e

_completion_actl() {
    local current_word="$2"
    local match_word="$2"
    local wrapper_current_word="$2"
    local cword="${COMP_CWORD}"
    local words_string="${COMP_WORDS[*]}"
    local line_prefix="${COMP_LINE:0:COMP_POINT}"
    local -a words=()

    if [[ -n "$line_prefix" ]]; then
        read -r -a words <<< "$line_prefix"
        if [[ "$line_prefix" =~ [[:space:]]$ ]]; then
            wrapper_current_word=""
            cword="${#words[@]}"
        elif [[ ${#words[@]} -gt 0 ]]; then
            wrapper_current_word="${words[${#words[@]}-1]}"
            cword="$(( ${#words[@]} - 1 ))"
        fi
        words_string="${words[*]}"
    fi

    if [[ "$wrapper_current_word" == --*"="* ]]; then
        match_word="${wrapper_current_word#*=}"
    elif [[ "$current_word" != "$wrapper_current_word" && "$current_word" != "" ]]; then
        match_word="$current_word"
    fi

    mapfile -t COMPREPLY < <(compgen -W "$(COMP_CWORD="${cword}" COMP_WORDS="${words_string}" /usr/share/alteratorctl/scripts/completion_wrapper "${1}" "${wrapper_current_word}" "${3}")" -- "$match_word")

    compopt +o nospace 2>/dev/null || true
    local candidate
    for candidate in "${COMPREPLY[@]}"; do
        if [[ "$candidate" == *= ]]; then
            compopt -o nospace 2>/dev/null || true
            break
        fi
    done
}

complete -o nosort -F _completion_actl alteratorctl
complete -o nosort -F _completion_actl actl
