#!/bin/bash
# skyctl completion

_get_skyctl_pos() {
  skyctl $1 --help | grep -E -o '^    [a-z-]+' | xargs
}

_get_skyctl_opt() {
  skyctl $1 --help | grep -E -o ' \--[a-z_-]+' | xargs
}

_skyctl()
{
  cur="${COMP_WORDS[COMP_CWORD]}"

  if [[ ${COMP_CWORD} == 1 ]]; then
    _subcommands="$(_get_skyctl_opt) "
    _subcommands+="$(_get_skyctl_pos)"
    COMPREPLY=( $(compgen -W "${_subcommands}" -- ${cur}) )
    return 0
  fi

  subcmd_1="${COMP_WORDS[1]}"

  case "${subcmd_1}" in
    list)
      if [[ ${COMP_CWORD} == 2 ]]; then
        _subcommands=`skyctl list-ns -f human | xargs`
      else
        _subcommands="$(_get_skyctl_opt ${subcmd_1}) "
      fi
      ;;

    get|list-scripts)
      if [[ ${COMP_CWORD} == 2 ]]; then
        _subcommands=`skyctl list-ns -f human | xargs`
      elif [[ ${COMP_CWORD} == 3 ]]; then
        _subcommands=`skyctl list -f human ${COMP_WORDS[2]} | xargs`
        if [[ "${_subcommands}" = "Empty list" ]]; then
            _subcommands=""
        fi
      else
        _subcommands="$(_get_skyctl_opt ${subcmd_1}) "
      fi
      ;;

    check|start|stop|restart|uninstall)
      if [[ ${COMP_CWORD} == 2 ]]; then
        _subcommands=`skyctl list-ns -f human | xargs`
      elif [[ ${COMP_CWORD} > 2 ]]; then
        _subcommands=`skyctl list -f human ${COMP_WORDS[2]} | xargs`
        if [[ "${_subcommands}" = "Empty list" ]]; then
            _subcommands=""
        fi
        _subcommands+=" $(_get_skyctl_opt ${subcmd_1}) "
      fi
      ;;

    run-script)
      if [[ ${COMP_CWORD} == 2 ]]; then
        _subcommands=`skyctl list-ns -f human | xargs`
      elif [[ ${COMP_CWORD} == 3 ]]; then
        _subcommands=`skyctl list -f human ${COMP_WORDS[2]} | xargs`
        if [[ "${_subcommands}" = "Empty list" ]]; then
            _subcommands=""
        fi
      elif [[ ${COMP_CWORD} == 4 ]]; then
        _subcommands=`skyctl list-scripts -f human ${COMP_WORDS[2]} ${COMP_WORDS[3]} 2>/dev/null | grep -E -o '^([a-z_-]+)' | xargs`
      else
        _subcommands="$(_get_skyctl_opt ${subcmd_1}) "
      fi
      ;;

    *)
      _subcommands="$(_get_skyctl_opt $subcmd_1) "
      ;;
  esac

  COMPREPLY=($(compgen -W "${_subcommands}" -- ${cur}))
  return 0
}

complete -F _skyctl skyctl
