#!/bin/bash
#-------------------------------------------------------------------------------
# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) 2008-2018 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 base
    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|cat-state|check-versions|checkpoint|diff|compare|documentation|browse|dump|edit|ext-trigger|external-trigger|get-directory|get-suite-config|get-config|get-suite-version|get-cylc-version|graph|graph-diff|gui|hold|insert|kill|list|ls|ls-checkpoints|monitor|nudge|ping|poll|register|release|unhold|reload|remove|report-timings|reset|restart|run|start|search|grep|set-verbosity|show|spawn|stop|shutdown|submit|single|suite-state|trigger|upgrade-run-dir|validate|view"


    if [[ ${COMP_CWORD} -eq 1 ]]; then
        CYLC_DIR=$(__cylc_get_cylc_dir)
        cylc_cmds=$(cd $CYLC_DIR/bin && ls 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_dir() {
    cylc version --long | sed "s/.*(\(.*\))/\1/"
}

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