#!/bin/bash
# update-alternatives(1) bash completion
#
# Copyright © 2002-2009 Guillaume Rousse <rousse@ccr.jussieu.fr>
# Copyright © 2004-2026 Ville Skyttä <ville.skytta@iki.fi>
# Copyright © 2009-2010 David Paleino <dapal@debian.org>
# Copyright © 2022-2024 Koichi Murase <myoga.murase@gmail.com>
# Copyright © 2026 Guillem Jover <guillem@debian.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

_comp_cmd_update_alternatives__installed()
{
  local i
  local -a opts
  for ((i = 1; i < cword; i++)); do
    if [[ ${words[i]} == --admindir ]]; then
      opts+=("--admindir" "${words[i + 1]}")
      break
    fi
  done
  _comp_compgen_split -- "$(command update-alternatives "${opts[@]}" --get-selections | cut -d\  -f1)"
}

_comp_cmd_update_alternatives()
{
  # shellcheck disable=SC2034
  local cur prev words cword comp_args
  _comp_initialize -- "$@" || return

  case $prev in
  --altdir | \
  --admindir | \
  --instdir | \
  --root)
    _comp_compgen_filedir -d
    return
    ;;
  --log)
    _comp_compgen_filedir
    return
    ;;
  --help | \
  --version)
    return
    ;;
  esac

  local mode="" args i

  # Find which mode to use and how many real args used so far.
  for ((i = 1; i < cword; i++)); do
    if [[ ${words[i]} == --@(install|remove|auto|display|query|list|get-selections|set-selections|config|all|remove-all|set) ]]; then
      mode=${words[i]}
      args=$((cword - i))
      break
    fi
  done

  case ${mode-} in
  --install)
    case $args in
    1 | 3)
      _comp_compgen_filedir
      ;;
    2)
      _comp_cmd_update_alternatives__installed
      ;;
    4)
      # Priority - no completions.
      ;;
    *)
      case $((args % 4)) in
      0 | 2)
        _comp_compgen_filedir
        ;;
      1)
        _comp_compgen -- -W '--slave'
        ;;
      3)
        _comp_cmd_update_alternatives__installed
        ;;
      esac
      ;;
    esac
    ;;
  --remove | \
  --set)
    case $args in
    1)
      _comp_cmd_update_alternatives__installed
      ;;
    2)
      _comp_compgen_filedir
      ;;
    esac
    ;;
  --auto | \
  --remove-all | \
  --display | \
  --query | \
  --list | \
  --config)
    _comp_cmd_update_alternatives__installed
    ;;
  *)
    _comp_compgen_help
    ;;
  esac
} && complete -F _comp_cmd_update_alternatives update-alternatives
