#!/usr/bin/env bash
#-------------------------------------------------------------------------------
# THIS FILE IS PART OF THE CYLC WORKFLOW 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 scan -t name 2>/dev/null)"
    workflow_cmds="broadcast|bcast|cat-log|check-versions|clean|compare|config|diff|dump|ext-trigger|external-trigger|get-workflow-version|get-cylc-version|graph|hold|insert|install|kill|list|log|ls|tui|pause|ping|play|poll|print|reinstall|release|unhold|reload|remove|report-timings|reset|scan|set-verbosity|show|set-outputs|stop|shutdown|single|workflow-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} =~ ^($workflow_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
