#compdef supervisord supervisorctl pidproxy
# ------------------------------------------------------------------------------
# Copyright (c) 2023 Github zsh-users - https://github.com/zsh-users
# All rights reserved.
#
# 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 supervisord tools v4.3.0 (https://github.com/Supervisor/supervisor)
#
# ------------------------------------------------------------------------------
# Authors
# -------
#
#  * Matt Black (https://github.com/mafrosis)
#  * dongweiming (https://github.com/dongweiming)
#  * Shohei YOSHIDA (https://github.com/syohex)
#
# ------------------------------------------------------------------------------

_supervisorctl() {
  local -a procs
  typeset -A opt_args
  local context state line
  local curcontext="$curcontext"
  local ret=1

  _arguments -C \
    {--configuration,-c}='[configuration file path (default /etc/supervisor.conf)]:filename:_files' \
    '(- *)'{--help,-h}'[print usage message and exit]' \
    {--interactive,-i}'[start an interactive shell after executing commands]' \
    {--serverurl,-s}='[URL on which supervisord server is listening (default "http://localhost:9001")]:url:_urls' \
    {--username,-u}='[username to use for authentication with server]:username:_users' \
    {--password,-p}='[password to use for authentication with server]:password' \
    {--history-file,-r}'[keep a readline history (if readline is available)]:filename:_files' \
    '1: :_supervisorctl_subcommands' \
    '*:: :->subcmds' && ret=0

  case $state in
    (subcmds)
      case "$words[1]" in
        (help)
          _arguments \
           '1: :_supervisorctl_subcommands' \
            && ret=0
          ;;
        (add|remove)
          _arguments \
            '1: :_supervisorctl_procs_groups' \
            && ret=0
          ;;
        (fg)
          _arguments \
            '1: :_supervisorctl_processes' \
            && ret=0
          ;;
        (pid|clear)
          _arguments \
            '*: :_supervisorctl_processes_all' \
            && ret=0
          ;;
        (restart|status)
          _arguments \
            '*:process_or_group:_supervisorctl_procs_and_group_prefixes' \
            && ret=0
          ;;
        (update)
          _arguments \
            '*: :_supervisorctl_groups' \
            && ret=0
          ;;
        (stop)
          _arguments \
            '*:running process or group:_supervisorctl_running_procs' \
            && ret=0
          ;;
        (start)
          _arguments \
            '*:stopped process or group:_supervisorctl_stopped_procs' \
            && ret=0
          ;;
        (signal)
          _arguments \
            '1:signal:_signals -s' \
            '*:running process or group:_supervisorctl_running_procs' \
            && ret=0
          ;;
        (tail)
          _arguments \
            '-f[Continuous tail of named process stdout]' \
            '-[last N *bytes* of process stdout]:number' \
            '1: :_supervisorctl_processes' \
            '2:output:(stdout stderr)' \
            && ret=0
          ;;
        (maintail)
          _arguments \
            '-f[Continuous tail of named process stdout]' \
            '-[last N *bytes* of process stdout]:number' \
            && ret=0
          ;;
      esac
  esac

  return 0
}

(( $+functions[_supervisorctl_subcommands] )) ||
_supervisorctl_subcommands() {
  local -a commands=(
    'add:Activates any updates in config for process/group'
    'avail:Display all configured processes'
    'clear:Clear single/multiple/all process log files'
    'exit:Exit the supervisor shell'
    'fg:Connect to a process in foreground mode'
    'maintail:tail of supervisor main log file'
    'open:Connect to a remote supervisord process. (for UNIX domain socket, use unix:///socket/path)'
    'pid:Get the PID of process/supervisord'
    'quit:Exit the supervisor shell'
    'reload:Restart the remote supervisord'
    'remove:Removes process/group from active config'
    "reread:Reload the daemon's configuration files"
    'restart:Restart process, group or all'
    'signal:Send signal to a process'
    'shutdown:Shut the remote supervisord down'
    'start:Start process, group or all'
    'status:Get process/group status info'
    'stop:Stop process, group or all'
    'tail:tail of process stdout'
    'update:Reload config and add/remove as necessary'
    'version:Show the version of the remote supervisord process'
    'help:Show help'
  )

  _describe -t commands 'command' commands "$@"
}

(( $+functions[_supervisorctl_processes] )) ||
_supervisorctl_processes() {
  local -a procs
  procs=(${(f)"$(_call_program processes supervisorctl avail | awk '{gsub(":","\\:", $1); print $1 }')"})
  if [[ "$1" = 'all' ]]; then
    procs+=(all)
  fi
  _describe 'processes' procs
}

(( $+functions[_supervisorctl_processes_all] )) ||
_supervisorctl_processes_all() {
  _supervisorctl_processes all
}

(( $+functions[_supervisorctl_procs_groups] )) ||
_supervisorctl_procs_groups() {
  local -a procs
  procs=(${(f)"$(_call_program processes supervisorctl status \
  | awk '{n=$1;gsub(":","\\:",n); printf "%s\n%s\n",n,substr($1,1,index($1,":")-1)}' \
  | uniq)"})
  _describe 'process and groups' procs
}

(( $+functions[_supervisorctl_procs_and_group_prefixes] )) ||
_supervisorctl_procs_and_group_prefixes() {
  _supervisorctl_collect_procs '.'
}

(( $+functions[_supervisorctl_running_procs] )) ||
_supervisorctl_running_procs() {
  _supervisorctl_collect_procs 'RUNNING'
}

(( $+functions[_supervisorctl_stopped_procs] )) ||
_supervisorctl_stopped_procs() {
  _supervisorctl_collect_procs 'STOPPED'
}

(( $+functions[_supervisorctl_collect_procs] )) ||
_supervisorctl_collect_procs() {
  if (( $words[(I)all] )); then
    return
  fi

  local pattern=$1

  local -a procs
  procs=(${(f)"$(_call_program processes supervisorctl status \
  | awk "/$pattern/"'{n=$1;gsub(":","\\:",n); printf "%s\n%s\\:\n",n,substr($1,1,index($1,":")-1)}' \
  | uniq)"})
  procs+=(all)
  _describe 'stoped processes or groups' procs
}

(( $+functions[_supervisorctl_groups] )) ||
_supervisorctl_groups() {
  if (( $words[(I)all] )); then
    return
  fi

  local -a groups
  groups=(${(f)"$(_call_program processes supervisorctl status \
  | awk '{printf "%s\n",substr($1,1,index($1,":")-1)}' \
  | uniq)"})
  groups+=(all)
  _describe 'groups' groups
}

case $service in
  (supervisord)
    _arguments \
      '(-c --configuration)'{-c,--configuration}'[configuration file path]:config file:_files' \
      '(-n --nodaemon)'{-n,--nodaemon}'[run in the foreground]' \
      '(-s --silent)'{-s,--silent}'[no longs to stdout]' \
      '(- *)'{-h,--help}'[print this usage message and exit]' \
      '(- *)'{-v,--version}'[print supervisord version number and exit]' \
      '(-u --user)'{-u,--user}'[run supervisord as given user]:user:_users' \
      '(-m --umask)'{-m,--umask}'[use given umask for daemon subprocess]:umask' \
      '(-d --directory)'{-d,--directory}'[directory to chdir to when daemonized]:directory:_files -/' \
      '(-l --logfile)'{-l,--logfile}'[logfile path]:logfile:_files' \
      '(-y --logfile_maxbytes)'{-y,--logfile_maxbytes}'[limit the max size of logfile]:max bytes' \
      '(-z --logfile_backups)'{-z,--logfile_backups}'[number of backups to keep when max bytes reached]:number of backups' \
      '(-e --loglevel)'{-e,--loglevel}'[log level]:level:(debug info warn error critical)' \
      '(-j --pidfile)'{-j,--pidfile}'[pid file path]:pid file:_files' \
      '(-i --identifier)'{-i,--identifier}'[identifier used for this instance of supervisord]:id' \
      '(-q --childlogdir)'{-q,--childlogdir}'[the log directory for child process logs]:log dir:_files -/' \
      '(-k --nocleanup)'{-k,--nocleanup}'[prevent the process from performing cleanup]' \
      '(-a --minfds)'{-a,--minfds}'[the minimum number of file descriptors for start success]:min fds' \
      '(-t --strip_ansi)'{-t,--strip_ansi}'[strip ansi escape codes from process output]' \
      '--profile_options[profile options]:profile option:_values -s , "field" cumulative calls callers'
    ;;
  (supervisorctl)
    _supervisorctl "$@"
    ;;
  (pidproxy)
    _arguments \
      '1:pid_file:_files' \
      '2:cmd:_command_names -e' \
      '*::argument:_normal'
    ;;
esac

# 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
