# bash completion for zpool-set(1). Source it from ~/.bashrc or install it as
# /usr/local/share/bash-completion/completions/zpool-set.

_zpool_set() {
  local cur prev
  COMPREPLY=()
  if declare -F _get_comp_words_by_ref >/dev/null 2>&1; then
    _get_comp_words_by_ref -n := cur prev
  else
    cur=${COMP_WORDS[COMP_CWORD]}
    prev=${COMP_WORDS[COMP_CWORD-1]}
  fi
  local props
  case $prev in
    -set)
      if [[ $cur == *=* ]]; then
        local p=${cur%%=*} v=${cur#*=}
        COMPREPLY=($(compgen -P "$p=" -W "$(zpool-set -describe "$p" 2>/dev/null | awk '/^    [a-z0-9]/ { print $1 }')" -- "$v"))
      else
        props=$(zpool-set -catalogue 2>/dev/null | awk '/ settable / { print $1 }' | grep -v '@$')
        COMPREPLY=($(compgen -S = -W "$props" -- "$cur"))
        compopt -o nospace 2>/dev/null
      fi
      declare -F __ltrim_colon_completions >/dev/null 2>&1 && __ltrim_colon_completions "$cur"
      return ;;
    -get|-reset|-where|-describe)
      props=$(zpool-set -catalogue 2>/dev/null | awk '/^  [a-z]/ { print $1 }' | grep -v '@$')
      local last=${cur##*,} head=
      [[ $cur == *,* ]] && head=${cur%,*},
      COMPREPLY=($(compgen -P "$head" -W "$props" -- "$last"))
      return ;;
    -enable)
      COMPREPLY=($(compgen -W "$(zpool-set -catalogue 2>/dev/null | awk '/^  feature@/ { sub(/^feature@/, "", $1); print $1 }')" -- "$cur"))
      return ;;
    -restore)
      COMPREPLY=($(compgen -f -- "$cur"))
      return ;;
    -vdev)
      local pool=$(zpool list -H -o name 2>/dev/null | head -1) w
      for w in "${COMP_WORDS[@]:1}"; do [[ $w != -* ]] && zpool list -H -o name "$w" >/dev/null 2>&1 && pool=$w; done
      COMPREPLY=($(compgen -W "root all $(zpool-set -vdevs "$pool" 2>/dev/null | awk 'NR > 1 { print $1 }')" -- "$cur"))
      return ;;
  esac
  if [[ $cur == -* ]]; then
    COMPREPLY=($(compgen -W '-version -mouse -features=false -color=false -list -local -get -set -reset -enable -vdev -vdevs -where -dump -restore -catalogue -describe -n -y -check -json -lenient' -- "$cur"))
    return
  fi
  COMPREPLY=($(compgen -W "$(zpool list -H -o name 2>/dev/null)" -- "$cur"))
}
complete -F _zpool_set zpool-set
