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

_dokku_complete_verify() {
  declare desc="shows bash completion"
  declare COMMAND="$1"
  local COMMANDS=""

  _dokku_complete_goals=$(cat "/var/cache/dokku-completion")

  while read -r fn; do
    if [[ -z "$COMMAND" ]] || [[ "$fn" == $COMMAND* ]]; then
      COMMANDS="${COMMANDS};${fn}"
    fi
  done <<< "$_dokku_complete_goals"

  echo "${COMMANDS#";"}"
}

_dokku() {
  local cur prev
  _get_comp_words_by_ref -n : cur

  if [[ ! -f "/var/cache/dokku-completion" ]] || [[ ! -s "/var/cache/dokku-completion" ]]; then
    dokku --quiet help --all | awk '/^    /{ print $1 }' | sort > "/var/cache/dokku-completion"
  fi

  opts=$(_dokku_complete_verify "${cur}")
  COMPREPLY=($(IFS=";" compgen -W "$opts" -- "$cur"))
  __ltrim_colon_completions "$cur"
} &&
complete -F _dokku dokku
