#!/bin/bash

# Moa bash completion!
#
#
#

__moa_is_moadir() {
	if [[ -e ".moa/template" ]]; then
		echo "yes";
	else
		echo "no"
	fi
}

__moa_get_template() {
	echo `moa template`
}

__moa_all_templates() {
	#return a list of all known moa templates
    echo `moa list`
}	


__moa_all_vars() {
	#return a list of all known moa templates
	if [[ $(__moa_is_moadir) == "yes" ]]
	then
	    echo `moa raw_parameters`
	fi
}		

_moa() 
{
    local cur prev opts shopts moacomms moacommand
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    		
    opts="--help --force --verbose --bg --title"
    shopts="-h -f -v -j -t"
    moacommand=""
       
    if [[ ${cur} == --* ]] ; then
        COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
        return 0
    fi

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

    if [[ ${prev} == moa ]]; then
	local commands=`moa raw_commands`;
    	COMPREPLY=( $(compgen -W "${commands}" -- ${cur}) )
        return 0
    fi
    
    #Find the currently entered command (if there is one)
        for x in $(seq 1 ${COMP_CWORD})
	  do
	  [[ ${COMP_WORDS[x]} == -* ]] && continue
	  moacommand=${COMP_WORDS[x]}
          for y in $(seq $((x+1)) ${COMP_CWORD})
	  do
	      [[ ${COMP_WORDS[y]} == -* ]] && continue
	      moaSecCommand=${COMP_WORDS[y]}
	      break
	  done
	  break
	done

    case "${moacommand}" in 
	
	new)
       	   local templates=$(__moa_all_templates)
       	   COMPREPLY=( $(compgen -W "${templates}" -- ${cur}) )   
            ;;
        set)
	    local vars=$(__moa_all_vars)
	    COMPREPLY=( $(compgen -o nospace -W "${vars}" -- ${cur}) )
	    ;;
	pack)
	    case "${moaSecCommand}" in 
		rm)
		    vars=$(__moa_all_packs)
		    COMPREPLY=( $(compgen -o nospace -W "${vars}" -- ${cur}) )
		    ;;
		unpack)
		    vars=$(__moa_all_packs)
		    COMPREPLY=( $(compgen -o nospace -W "${vars}" -- ${cur}) )
		    ;;
		list)
		    ;;
		*)
		    vars="unpack list args rm"
		    COMPREPLY=( $(compgen -o nospace -W "${vars}" -- ${cur}) )
		    ;;	       
	    esac
	    ;;
	unpack)
	    local vars=$(__moa_all_packs)
	    COMPREPLY=( $(compgen -o nospace -W "${vars}" -- ${cur}) )
	    ;;
        *)
        	;;
    esac
               	
}
complete -o nospace -o default -o bashdefault -F _moa moa
