# Bash completion script for id3 mass tagger
# To use this script you should have the bash-completion package installed

# very simple right now. possible extensions:
# - ID3v2 frames lists for -w

_id3mtag() {
	local cur prev arg n
	local IFS=$'\n'

	COMPREPLY=()
	cur="${COMP_WORDS[COMP_CWORD]}"
	prev="${COMP_WORDS[COMP_CWORD-1]}"

	# don't complete filenames if argument matches an option of the following:
	# -talnygc, -fq, -s, -wXXXX, -D; or if the -m switch is being used

	for ((n=1; n<COMP_CWORD; n++)); do
		arg="${COMP_WORDS[n]}"
		if [ "${arg:0:1}" = "-" -a "$arg" != "--" ]; then
			[ "${arg//[!m]/}" != "" ] && { COMPREPLY=(); return; }
			if [ "${arg::2}" = "--" ]; then
				${COMP_WORDS[0]} --help | grep -qe "$arg <[a-z]*>" && let n++
			else
				arg="${arg//[!talnygcDfqsw]/}"
				n="$((n+${#arg}))"
			fi
		else
			n=0
			break
		fi
	done
	if [ $n -eq $COMP_CWORD -a "${cur::2}" = "--" ]; then
		# generate options from --help
		COMPREPLY=( $( compgen -W "$(${COMP_WORDS[0]} --help | grep -oe '--[-=a-zA-Z]\+' | sed '/TYPE/{p;s///;}' )" -- "$cur" ) )
	elif [ $n -le $COMP_CWORD ] || [ $((n-1)) -eq $COMP_CWORD -a \( "$prev" = "-D" -o "$arg" = "--duplicate" \) ]; then
		# generate quoted filenames
		COMPREPLY=( $( compgen -f -X '!*.mp3' -- "$cur" | sed '/[^[:alnum:]./]/s/.*/"&"/' ) )
	fi
} &&
complete -F _id3mtag id3
