# completion script for transcrypt

_files_and_dirs() {
	local IFS=$'\n'
	local LASTCHAR=' '

	COMPREPLY=( $(compgen -o plusdirs -f -- "${COMP_WORDS[COMP_CWORD]}") )

	if [[ ${#COMPREPLY[@]} -eq 1 ]]; then
		[[ -d "$COMPREPLY" ]] && LASTCHAR='/'
		COMPREPLY=$(printf '%q%s' "$COMPREPLY" "$LASTCHAR")
	else
		for ((i=0; i < ${#COMPREPLY[@]}; i++)); do
			[[ -d "${COMPREPLY[$i]}" ]] && COMPREPLY[$i]=${COMPREPLY[$i]}/
		done
	fi
}

_transcrypt() {
	local cur prev opts
	COMPREPLY=()
	cur="${COMP_WORDS[COMP_CWORD]}"
	prev="${COMP_WORDS[COMP_CWORD-1]}"
	opts="-c -p -y -d -r -f -F -u -l -s -e -i -C -v -h \
	      --cipher --password --set-openssl-path --yes --display --rekey --flush-credentials --force --uninstall --upgrade --list --show-raw --export-gpg --import-gpg --context --list-contexts --version --help"

	case "${prev}" in
		-c | --cipher)
			local ciphers=$(openssl list-cipher-commands)
			COMPREPLY=( $(compgen -W "${ciphers}" -- ${cur}) )
			return 0
			;;
		-p | --password)
			return 0
			;;
		-s | --show-raw)
			_files_and_dirs
			return 0
			;;
		-e | --export-gpg)
			return 0
			;;
		-i | --import-gpg)
			_files_and_dirs
			return 0
			;;
		*)
			;;
	esac

	COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
	COMPREPLY=$(printf '%q%s' "$COMPREPLY" ' ')
}

complete -o nospace -F _transcrypt transcrypt
