# bash completion for addspn                                  -*- shell-script -*-

_addspn()
{
  local cur prev hosts spn_classes
  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  prev="${COMP_WORDS[COMP_CWORD - 1]}"
  hosts=$(compgen -A hostname | grep -vE '^(localhost|parrot|ip6-localhost|ip6-loopback|ip6-allnodes|ip6-allrouters|ff02::1|ff02::2|::1|)$')

  if [[ $cur == -* ]]; then
    opts="$(_parse_usage addspn) $(_parse_help addspn --help)"
    COMPREPLY=( $(compgen -W "$opts" -- "$cur") )
  fi

  if [[ "$prev" == "-T" || "$prev" == "--target-type" ]]; then
    COMPREPLY=( $(compgen -W "samname hostname" -- "$cur") )
  fi

  # According to the setspn page from msdn, there are way more spn classes, but most of them are probably not gonna be used very often.
  spn_classes="HTTP/ HTTPS/ LDAP/ CIFS/ HOST/ RestrictedKrbHost/ MSSQLSvc/ TERMSRV/ WSMAN/ SMTP/ IMAP/ POP/ DNS/ GC/ RPC/ DCOM/ FTP/"

  # Made by yours truly, chatgpt
  if [[ "$prev" == "-s" || "$prev" == "--spn" ]]; then
    if [[ "$cur" == */* ]]; then
      prefix="${cur%%/*}/"
      cur="${cur#*/}"

      COMPREPLY=( $(printf '%s\n' "$hosts" | awk -v cur="$cur" '
        index(tolower($0), tolower(cur)) == 1 { print }
      ' | sed "s|^|$prefix|") )

    elif [[ -z "$cur" ]]; then
      COMPREPLY=( $(compgen -W "$spn_classes" -- "") )

    else
      COMPREPLY=( $(printf '%s\n' $spn_classes | awk -v cur="$cur" '
        index(tolower($0), tolower(cur)) == 1 { print }
      ') )
    fi

    compopt -o nospace
    return 0
  fi



}

complete -o bashdefault -o default -F _addspn addspn

# ex: filetype=sh

