#!/bin/bash
#-------------------------------------------------------------------------------
# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) 2008-2017 NIWA
#
# 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 prev opts base
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"

    CYLC_DIR=$(__cylc_get_cylc_dir)
    cylc_cmds=$(cd $CYLC_DIR/bin && ls cylc-* | sed "s/^cylc-//g")

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

}

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

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