#!/bin/bash

# =========================================================================
# This is a bash-completion script assuming the formatted printout is
# according to Boost program options.  Boost prints out program
# options like (e.g.):
#   --opt1             Non-argument option
#   --opt2 arg         Option with argument
#   -O [ --opt3 ] arg  Long and short options with argument
#
# =========================================================================

# Private utilities.
libexec=$(cd "${BASH_SOURCE%/*}/../libexec" && pwd -P)

# Arguments.
output=$1
exec=$2
user=${3:-""}

filter="${libexec}/filter-program-options"

[[ -x "${filter}" ]] || \
  { echo "Unable to find required companion program filter-program-options at $filter" 1>&2
  exit 1; }

options=$("${exec}" -h 2>&1 | "${filter}")

# Sometimes it's necessary to rename the bash function since the exec
# my have a hyphen in it.
fcn=${exec//-/_}

cat >$output <<EOF
# Bash completions not supported by csh--bail out early.
test \$?shell = 1 && exit

_$fcn()
{
    local cur prev opts
    COMPREPLY=()
    cur="\${COMP_WORDS[COMP_CWORD]}"
    prev="\${COMP_WORDS[COMP_CWORD-1]}"
    opts="$options"

    # User-provided completions
    $([ "$user" == "" ] && echo "# (none provided)" || cat $user)

    # Standard completions
    if [[ \${cur} == -* ]] ; then
        COMPREPLY=( \$(compgen -W "\${opts}" -- \${cur}) )
        return 0
    fi

    COMPREPLY=()
    return 0
}
complete -F _$fcn -o filenames -A file $exec
EOF
