#!/bin/bash
#-------------------------------------------------------------------------------
# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#-------------------------------------------------------------------------------
# USAGE
#     Sets up bash auto-completion for cylc commands.
#
#     Users should source this file in their ~/.bashrc, using something
#     like this:
#     if [[ $- =~ i && -f /path/to/cylc-bash-completion ]]; then
#         . /path/to/cylc-bash-completion
#     fi
#     where /path/to/cylc-bash-completion is replaced by the path to
#     this file.
#
#     Administrators may want to place this file in the
#     /etc/bash_completion.d/ (or equivalent) directory.
#-------------------------------------------------------------------------------

_cylc() {

    local cur sec opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    sec="${COMP_WORDS[1]}"
    opts="$(cylc print -x -y 2>/dev/null)"
    suite_cmds="broadcast|bcast|cat-log|log|check-versions|checkpoint|diff|compare|dump|edit|ext-trigger|external-trigger|get-directory|get-suite-config|get-config|get-suite-version|get-cylc-version|graph|graph-diff|hold|insert|kill|list|ls|ls-checkpoints|tui|nudge|ping|poll|print|register|release|unhold|reload|remove|report-timings|reset|restart|run|start|scan|search|grep|set-verbosity|show|spawn|stop|shutdown|single|suite-state|test-battery|trigger|validate|view|warranty"


    if [[ ${COMP_CWORD} -eq 1 ]]; then
        CYLC_BIN_DIR=$(__cylc_get_cylc_bin_dir)
        cylc_cmds="$(cd "$CYLC_BIN_DIR" && echo cylc-* | sed "s/^cylc-//g")"
        COMPREPLY=("$(compgen -W "${cylc_cmds}" -- "${cur}")")
    elif [[ ${sec} =~ ^($suite_cmds)$ ]]; then
        COMPREPLY=( "$(compgen -W "${opts}" -- "${cur}")" )
    fi
    return 0
}

__cylc_get_cylc_bin_dir() {
    cylc version --long | sed "s/.*(\(.*\))/\1/"
}

complete -o bashdefault -o default -o nospace -F _cylc cylc
