#compdef knife
# ------------------------------------------------------------------------------
# Copyright (c) 2009-2015 Robby Russell and contributors (see
# https://github.com/ohmyzsh/ohmyzsh/graphs/contributors)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# ------------------------------------------------------------------------------
# Description
# -----------
#
#  Completion script for Chef's knife (https://www.chef.io/).
#
#  Source: https://github.com/ohmyzsh/ohmyzsh/blob/22fed4f/plugins/knife/_knife
#
# ------------------------------------------------------------------------------
# Authors
# -------
#
#  * Frank Louwers (https://github.com/franklouwers)
#  * Mark Cornick (https://github.com/markcornick)
#
# ------------------------------------------------------------------------------


# You can override the path to knife.rb and your cookbooks by setting
# KNIFE_CONF_PATH=/path/to/my/.chef/knife.rb
# KNIFE_COOKBOOK_PATH=/path/to/my/chef/cookbooks
# If you want your local cookbooks path to be calculated relative to where you are then
# set the below option
# KNIFE_RELATIVE_PATH=true
# Read around where these are used for more detail.

# knife has a very special syntax, some example calls are:
# knife status
# knife cookbook list
# knife role show ROLENAME
# knife data bag show DATABAGNAME
# knife role show ROLENAME --attribute ATTRIBUTENAME
# knife cookbook show COOKBOOKNAME COOKBOOKVERSION recipes

# The -Q switch in compadd allow for completions of things like "data bag" without having to go through two rounds of completion and avoids zsh inserting a \ for escaping spaces
_knife() {
  # These flags should be available everywhere according to man knife
  local -a knife_general_flags; knife_general_flags=(--help --server-url --key --config --editor --format --log_level --logfile --no-editor --user --print-after --version --yes)

  local curcontext="$curcontext" state line
  typeset -A opt_args
  local -a cloudproviders; cloudproviders=(bluebox ec2 rackspace slicehost terremark)
  _arguments \
    '1: :->knifecmd' \
    '2: :->knifesubcmd' \
    '3: :->knifesubcmd2' \
    '4: :->knifesubcmd3' \
    '5: :->knifesubcmd4' \
    '6: :->knifesubcmd5'

  case $state in
  knifecmd)
    compadd -Q "$@" bootstrap client configure cookbook "cookbook site" "data bag" diff exec environment user index node recipe role search solo ssh status upload vault windows "$cloudproviders[@]"
    ;;
  knifesubcmd)
    case $words[2] in
    bluebox|ec2|rackspace|slicehost|terremark)
      compadd "$@" server images
      ;;
    client)
      compadd -Q "$@" "bulk delete" list create show delete edit reregister
      ;;
    configure)
      compadd "$@" client
      ;;
    cookbook)
      compadd -Q "$@" test list create download delete "metadata from" show "bulk delete" metadata upload
      ;;
    diff)
      _arguments '*:file or directory:_files -g "*"'
      ;;
    environment)
      compadd -Q "$@" list create delete edit show "from file"
      ;;
    user)
      compadd -Q "$@" create delete edit list reregister show
      ;;
    node)
      compadd -Q "$@" "from file" create show edit delete list run_list "bulk delete"
      ;;
    recipe)
      compadd "$@" list
      ;;
    role)
      compadd -Q "$@" "bulk delete" create delete edit "from file" list show
      ;;
    solo)
      compadd "$@" bootstrap clean cook init prepare
      ;;
    upload)
      _arguments '*:file or directory:_files -g "*"'
      ;;
    vault)
      compadd -Q "$@" create decrypt delete edit remove "rotate all keys" "rotate keys" show update
      ;;
    windows)
      compadd "$@" bootstrap
      ;;
    *)
      _arguments '2:Subsubcommands:($(_knife_options1))'
      ;;
    esac
    ;;
  knifesubcmd2)
    case $words[3] in
    server)
      compadd "$@" list create delete
      ;;
    images)
      compadd "$@" list
      ;;
    site)
      compadd "$@" vendor show share search download list unshare
      ;;
    show|delete|edit|update)
      _arguments '3:Subsubcommands:($(_knife_list_remote "$words[2]"))'
      ;;
    upload|test)
      _arguments '3:Subsubcommands:($(_call_function - "_knife_list_local_$words[2]s") --all)'
      ;;
    list)
      compadd -a "$@" knife_general_flags
      ;;
    bag)
      compadd -Q "$@" show edit list "from file" create delete
      ;;
    bootstrap|clean|cook|prepare)
      compadd "$@" nodes/*.json(N:t:r)
      ;;
    init)
      compadd "$@" ./*(/N:t)
      ;;
    *)
      _arguments '3:Subsubcommands:($(_knife_options2))'
      ;;
    esac
    ;;
  knifesubcmd3)
    case "$words[3]" in
    show)
      case "$words[2]" in
      cookbook)
        versioncomp=1
        _arguments '4:Cookbookversions:($(_knife_cookbook_versions) latest)'
        ;;
      node|client|role)
        compadd "$@" --attribute
        ;;
      vault)
        _arguments '4:Keys:($(_knife_list_remote "$words[2]" "$words[4]"))'
        ;;
      esac
      ;;
    update)
      case "$words[2]" in
      vault)
        _arguments '4:Keys:($(_knife_list_remote "$words[2]" "$words[4]"))'
        ;;
      esac
      ;;
    esac
    case "$words[4]" in
    show|edit)
      _arguments '4:Subsubsubcommands:($(_knife_list_remote "$words[2]" "$words[3]"))'
      ;;
    file)
      case "$words[2]" in
      environment)
        _arguments '*:files:_path_files -g "*.(rb|json)" -W "$(_knife_root)/environments"'
        ;;
      node)
        _arguments '*:files:_path_files -g "*.(rb|json)" -W "$(_knife_root)/nodes"'
        ;;
      role)
        _arguments '*:files:_path_files -g "*.(rb|json)" -W "$(_knife_root)/roles"'
        ;;
      *)
        _arguments '*:Subsubcommands:($(_knife_options3))'
        ;;
      esac
      ;;
    list)
      compadd -a "$@" knife_general_flags
      ;;
    *)
      _arguments '*:Subsubcommands:($(_knife_options3))'
      ;;
    esac
    ;;
  knifesubcmd4)
    if ((versioncomp > 0)); then
      compadd "$@" attributes definitions files libraries providers recipes resources templates
    else
      case "$words[5]" in
      file)
        _arguments '*:directory:_path_files -/ -W "$(_knife_root)/data_bags" -qS \ '
        ;;
      *) _arguments '*:Subsubcommands:($(_knife_options2))' ;;
      esac
    fi
    ;;
  knifesubcmd5)
    case "$words[5]" in
    file)
      _arguments '*:files:_path_files -g "*.json" -W "$(_knife_root)/data_bags/$words[6]"'
      ;;
    *)
      _arguments '*:Subsubcommands:($(_knife_options3))'
      ;;
    esac
    ;;
  esac
}

# Helper functions to provide the argument completion for several depths of commands
_knife_options1() {
  local line
  for line in $(_call_program commands knife "$words[2]" --help | grep -v "^knife"); do
    echo $line | grep "\-\-"
  done
}

_knife_options2() {
  local line
  for line in $(_call_program commands knife "$words[2]" "$words[3]" --help | grep -v "^knife"); do
    echo $line | grep "\-\-"
  done
}

_knife_options3() {
  local line
  for line in $(_call_program commands knife "$words[2]" "$words[3]" "$words[4]" --help | grep -v "^knife"); do
    echo $line | grep "\-\-"
  done
}

# get a list of objects of type x on the server
_knife_list_remote() {
  case "$*" in
    role|client|node|cookbook|"cookbook site"|"data bag"|environment|user|vault)
      _call_program commands knife "$@" list --format json \
        | grep \" \
        | awk '{print $1}' \
        | awk -F"," '{print $1}' \
        | awk -F"\"" '{print $2}'
      ;;
    "vault "*)
      _call_program commands knife vault show "$2" --format json \
        | grep \" \
        | awk '{print $1}' \
        | awk -F"," '{print $1}' \
        | awk -F"\"" '{print $2}'
      ;;
  esac
}

# The chef_x_local functions use the knife config to find the paths of relevant objects x to be uploaded to the server
_knife_list_local_cookbooks() {
  if [ $KNIFE_RELATIVE_PATH ]; then
    local cookbook_path="$(_knife_root)/cookbooks"
  else
    local knife_rb="${KNIFE_CONF_PATH:-${HOME}/.chef/knife.rb}"
    if [ -f ./.chef/knife.rb ]; then
      knife_rb="./.chef/knife.rb"
    fi
    local cookbook_path="${KNIFE_COOKBOOK_PATH:-$(grep -s cookbook_path "$knife_rb" | awk 'BEGIN {FS = "[" }; {print $2}' | sed 's/\,//g' | sed "s/'//g" | sed 's/\(.*\)]/\1/' | cut -d '"' -f2)}"
  fi

  local i
  for i in $cookbook_path; do
    ls $i
  done
}

# This function extracts the available cookbook versions on the chef server
_knife_cookbook_versions() {
  _call_program commands knife cookbook show "$words[4]" \
    | grep -v "$words[4]" \
    | grep -v -E '\]|\[|\{|\}' \
    | sed 's/ //g' \
    | sed 's/"//g'
}

# Searches up from current directory to find the closest folder that has a .chef folder
# Useful for the knife upload/from file commands
_knife_root() {
  local directory="$PWD"
  while [ $directory != '/' ]; do
    test -e "$directory/.chef" && echo "$directory" && return
    directory="${directory:h}"
  done
}

_knife "$@"

# Local Variables:
# mode: Shell-Script
# sh-indentation: 2
# indent-tabs-mode: nil
# sh-basic-offset: 2
# End:
# vim: ft=zsh sw=2 ts=2 et
