#!/bin/bash
# Shell completion script for distrobox (bash).
#
# Mirrors urfave/cli v3.5.0's bash autocomplete template, with one
# fix: when the current word is exactly "--" (user typed
# `distrobox <cmd> --<TAB>`), don't inject it into the request line.
# urfave's checkShellCompleteFlag bails out as soon as it sees "--"
# in argv, so injecting it ahead of --generate-shell-completion
# silently disables completion. Skipping the injection lets the
# binary's ShellComplete callback emit the full candidate set;
# bash filters by prefix via compgen.

# Macs have bash3 for which the bash-completion package doesn't include
# _init_completion. This is a minimal version of that function.
__distrobox_init_completion() {
  COMPREPLY=()
  _get_comp_words_by_ref "$@" cur prev words cword
}

__distrobox_bash_autocomplete() {
  if [[ "${COMP_WORDS[0]}" != "source" ]]; then
    local cur opts base words
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    if declare -F _init_completion >/dev/null 2>&1; then
      _init_completion -n "=:" || return
    else
      __distrobox_init_completion -n "=:" || return
    fi
    words=("${words[@]:0:$cword}")
    if [[ "$cur" == "-"* && "$cur" != "--" ]]; then
      requestComp="${words[*]} ${cur} --generate-shell-completion"
    else
      requestComp="${words[*]} --generate-shell-completion"
    fi
    opts=$(eval "${requestComp}" 2>/dev/null)
    COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
    return 0
  fi
}

complete -o bashdefault -o default -o nospace -F __distrobox_bash_autocomplete distrobox
