#!/bin/bash
shopt -s progcomp

_charm_official_charms() {
    charm list | awk -Flp:charms/ '/^lp:charms/ { print $2 }'
}

_charm () {
    local cur cmds cmdIdx cmd cmdOpts fixedWords i globalOpts
    local curOpt optEnums
    local IFS=$' \n'

    COMPREPLY=()
    cur=${COMP_WORDS[COMP_CWORD]}
    cmds=`charm --list`
    globalOpts=( -h )

    # do ordinary expansion if we are anywhere after a -- argument
    for ((i = 1; i < COMP_CWORD; ++i)); do
        [[ ${COMP_WORDS[i]} == "--" ]] && return 0
    done

    # find the command; it's the first word not starting in -
    cmd=
    for ((cmdIdx = 1; cmdIdx < ${#COMP_WORDS[@]}; ++cmdIdx)); do
        if [[ ${COMP_WORDS[cmdIdx]} != -* ]]; then
            cmd=${COMP_WORDS[cmdIdx]}
            break
        fi
    done

    # complete command name if we are not already past the command
    if [[ $COMP_CWORD -le cmdIdx ]]; then
        COMPREPLY=( $( compgen -W "$cmds ${globalOpts[*]}" -- "$cur" ) )
        return 0
    fi

    # find the option for which we want to complete a value
    curOpt=
    if [[ $cur != -* ]] && [[ $COMP_CWORD -gt 1 ]]; then
        curOpt=${COMP_WORDS[COMP_CWORD - 1]}
        if [[ "$curOpt" == = ]]; then
            curOpt=${COMP_WORDS[COMP_CWORD - 2]}
        elif [[ "$cur" == : ]]; then
            cur=
            curOpt="$curOpt:"
        elif [[ "$curOpt" == : ]]; then
            curOpt=${COMP_WORDS[COMP_CWORD - 2]}:
        fi
    fi

    cmdOpts=( )
            cmdOpts=(--help)
    optEnums=( )
    fixedWords=( )
    case "$cmd" in
        get)
            for charm in $(_charm_official_charms) ; do
               cmdOpts+=($charm)
            done 
            ;;
        *)
            ;;
    esac

    IFS=$'\n'
    if [[ "$cur" == = ]] && [[ ${#optEnums[@]} -gt 0 ]]; then
        # complete directly after "--option=", list all enum values
        COMPREPLY=( "${optEnums[@]}" )
        return 0
    else
        fixedWords=( "${cmdOpts[@]}"
                     "${globalOpts[@]}"
                     "${optEnums[@]}"
                     "${fixedWords[@]}" )
    fi

    if [[ ${#fixedWords[@]} -gt 0 ]]; then
        COMPREPLY=( $( compgen -W "${fixedWords[*]}" -- "$cur" ) )
    fi

    return 0
}

complete -F _charm -o default charm
