_freevo()
{
	local options scripts cur prev

	FREEVO_HOMEDIR=/home/eirikm/src/freevo/freevo-new
	COMPREPLY=()

	freevo_options=('-fs')
	options=('start stop --help')
	scripts=('bluetooth cache daemon imdb makelircrc makestationlist plugins recordserver remote schedulefavorites setup tv_grab vtrelease webserver')
	cur=${COMP_WORDS[COMP_CWORD]}
	prev=${COMP_WORDS[COMP_CWORD-1]}

	# return possible completions for word right after freevo
	if [ $COMP_CWORD -eq 1 ]; then
		COMPREPLY=( $( compgen -W "$freevo_options $options $scripts" -- $cur ) )
                return 0
	fi

	
	if [ $COMP_CWORD -gt 1 ]; then
		# if previous word was an option don't return any completions
		for last in "$freevo_options $options"; do
			if [ "$last" == "$prev" ]; then
				return 0
			fi
		done

		case "$prev" in
			bluetooth)
				COMPREPLY=( $( compgen -W '--help' -- $cur ) )
				return 0
				;;
			cache)
				COMPREPLY=( $( compgen -W '--rebuild --help' -- $cur ) )
				return 0
				;;
			daemon)
				COMPREPLY=( $( compgen -W "$options" -- $cur ) )
				return 0
				;;
			imdb)
				# not fully implemented
				COMPREPLY=( $( compgen -W '-s -g --romdrives= --help' -- $cur ) )
				return 0;
				;;
			makelircrc)
				# not fully implemented
				COMPREPLY=( $( compgen -W '-w --help' -- $cur ) )
				return 0
				;;
			makestationlist)
				COMPREPLY=( $( compgen -W '--help' -- $cur ) )
				return 0
				;;
			plugins)
				COMPREPLY=( $( compgen -W '-l -i -a --help' -- $cur ) )
				return 0
				;;
			recordserver)
				# --help missing
				#COMPREPLY=( $( compgen -W "$options" -- $cur ) )
				COMPREPLY=( $( compgen -W 'start stop' -- $cur ) )
				return 0
				;;
			remote)
				COMPREPLY=( $( compgen -W '--help' -- $cur ) )
				return 0
				;;
			schedulefavorites)
				# --help missing
				#COMPREPLY=( $( compgen -W '--help' -- $cur ) )
				return 0
				;;
			setup)
				COMPREPLY=( $( compgen -W '--geometry= --display= --tv= --chanlist= --sysfirst --help' -- $cur ) )
				return 0
				;;
			tv_grab)
				COMPREPLY=( $( compgen -W '--help -query' -- $cur ) )
				return 0
				;;
			vtrelease)
				COMPREPLY=( $( compgen -W '--help' -- $cur ) )
				return 0
				;;
			webserver)
				COMPREPLY=( $( compgen -W 'start stop --help' -- $cur ) )
				return 0
				;;
		esac

		# special treatment of "plugins -i"
		if [[ "${COMP_WORDS[COMP_CWORD-2]}" == "plugins" ]] && [[ "$prev" == "-i" ]]; then  
			COMPREPLY=( $( compgen -W "$( $FREEVO_HOMEDIR/freevo plugins -l|grep -E "^\w+"|grep -v -E "^\w+:$"|cut -d' ' -f1 )" -- $cur ) )
		fi
	fi
	return 0
}

complete -F _freevo freevo
