# Check for bash
[ -z "$BASH_VERSION" ] && return

__toolbox_containers() {
  toolbox list -c 2>/dev/null | tail -n +2 2>/dev/null | cut -d " " -f 3 2>/dev/null
}

__toolbox_distros() {
  echo "fedora"
  echo "rhel"
}

__toolbox_images() {
  toolbox list -i 2>/dev/null | tail -n +2 2>/dev/null | cut -d " " -f 3 2>/dev/null
}

__toolbox() {
  local MIN_VERSION=32
  local RAWHIDE_VERSION=34

  local commands="create enter help init-container list rm rmi run"
  local global_options="--assumeyes --help --log-level --log-podman"
  local log_levels="debug info warn error fatal panic"

  declare -A options
  local options=([create]="--distro --image --release" \
                 [enter]="--distro --release" \
                 [help]="$commands" \
                 [init-container]="--home --home-link --monitor-host --shell --uid --user" \
		 [list]="--containers --images" \
		 [rm]="--all --force" \
		 [rmi]="--all --force" \
		 [run]="--container --distro --release")

  _init_completion -s || return

  if [ "${COMP_CWORD}" -eq 1 ]; then
    mapfile -t COMPREPLY < <(compgen -W "$global_options $commands" -- "$2")
    return 0
  fi

  # If a global option is mentioned, don't mention it anymore
  for option in $global_options; do
    if [[ "${COMP_LINE}" =~ "$option" ]]; then
      global_options="${global_options/$option}"
    fi
  done

  # If a command is mentioned, don't mention any more commands
  local command
  for cmd in $commands; do
    if [[ "${COMP_LINE}" =~ "$cmd" ]]; then
      commands=""
      command="$cmd"
    fi
  done

  case "$prev" in
    --assumeyes | -y | --help | -h | --verbose | -v | --log-podman)
      mapfile -t COMPREPLY < <(compgen -W "$global_options $commands" -- "$2")
      return 0
      ;;
    --container | -c)
      mapfile -t COMPREPLY < <(compgen -W "$(__toolbox_containers)" -- "$2")
      return 0
      ;;
    --distro | -d)
      mapfile -t COMPREPLY < <(compgen -W "$(__toolbox_distros)" -- "$2")
      return 0
      ;;
    --image | -i)
      mapfile -t COMPREPLY < <(compgen -W "$(__toolbox_images)" -- "$2")
      return 0
      ;;
    --release | -r)
      mapfile -t COMPREPLY < <(compgen -W "$(seq $MIN_VERSION $RAWHIDE_VERSION)" -- "$2")
      return 0
      ;;
    --log-level)
      mapfile -t COMPREPLY < <(compgen -W "$log_levels" -- "$2")
      return 0
      ;;
  esac

  local extra_comps
  case "$command" in
    rm | enter)
      extra_comps="$(__toolbox_containers)"
      ;;&
    rmi)
      extra_comps="$(__toolbox_images)"
      ;;&
    *)
      mapfile -t COMPREPLY < <(compgen -W "${options[$command]} $extra_comps" -- "$2")
      return 0;
      ;;
  esac
}

complete -F __toolbox toolbox
