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

_facl() {
  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
  case $prev in
    -scope)
      COMPREPLY=($(compgen -W 'this propagate replace' -- "$cur"))
      return ;;
    -set)
      COMPREPLY=($(compgen -W "$(facl -templates 2>/dev/null | awk 'NR > 1 { print "@" $1 }')" -- "$cur"))
      return ;;
    -effective)
      case $cur in
        user:*)  COMPREPLY=($(compgen -P user: -u -- "${cur#user:}")) ;;
        group:*) COMPREPLY=($(compgen -P group: -g -- "${cur#group:}")) ;;
        *)       COMPREPLY=($(compgen -W 'user: group:' -- "$cur"))
                 compopt -o nospace 2>/dev/null ;;
      esac
      declare -F __ltrim_colon_completions >/dev/null 2>&1 && __ltrim_colon_completions "$cur"
      return ;;
    -chown)
      case $cur in
        *:*) COMPREPLY=($(compgen -P "${cur%%:*}:" -g -- "${cur#*:}")) ;;
        *)   COMPREPLY=($(compgen -u -- "$cur")) ;;
      esac
      declare -F __ltrim_colon_completions >/dev/null 2>&1 && __ltrim_colon_completions "$cur"
      return ;;
    -where)
      case $cur in
        user:*)  COMPREPLY=($(compgen -P user: -u -- "${cur#user:}")) ;;
        group:*) COMPREPLY=($(compgen -P group: -g -- "${cur#group:}")) ;;
        *)       COMPREPLY=($(compgen -W 'user: group: owner@ group@ everyone@' -- "$cur"))
                 compopt -o nospace 2>/dev/null ;;
      esac
      declare -F __ltrim_colon_completions >/dev/null 2>&1 && __ltrim_colon_completions "$cur"
      return ;;
    -show|-delete-template)
      COMPREPLY=($(compgen -W "$(facl -templates 2>/dev/null | awk 'NR > 1 { print $1 }')" -- "$cur"))
      return ;;
    -fs)
      COMPREPLY=($(compgen -W 'zfs ufs zfs:restricted zfs:passthrough zfs:passthrough-x zfs:noallow zfs:discard' -- "$cur"))
      return ;;
    -from|-restore)
      compopt -o filenames 2>/dev/null
      COMPREPLY=($(compgen -f -- "$cur"))
      return ;;
    -chmod|-save|-add|-remove|-modify|-at)
      return ;;
  esac
  if [[ $cur == -* ]]; then
    COMPREPLY=($(compgen -W '-version -mouse -fs -set -from -add -remove -modify -at -check -save -show -delete-template -templates -audit -fix -scope -n -y -effective -chmod -chown -R -where -nontrivial -dump -restore -json' -- "$cur"))
    return
  fi
  compopt -o filenames 2>/dev/null
  COMPREPLY=($(compgen -f -- "$cur"))
}
complete -F _facl facl
