#!/bin/bash
# fontlinge_complete
#
# (c) Christian Boltz 2004-2005 / GPL
#
#
# parts of this completion rules are taken from
#
#   bash_completion - some programmable completion functions for bash 2.05b
#   Copyright (C) Ian Macdonald <ian@caliban.org> / GPL
#   http://www.caliban.org/bash/index.shtml#completion


# Turn on extended globbing and programmable completion
shopt -s extglob progcomp

# This function performs file and directory completion. It's better than
# simply using 'compgen -f', because it honours spaces in filenames.
# $1: If passed -d, it completes only on directories. If passed anything else,
#     it's assumed to be a file glob to complete on.
# $2: show options also? Pass "1" if you want it.
_fontlinge_filedir()
{
	local IFS=$'\t\n' # xspec
	local i pattern showopts

	pattern="-f"
	test -n "$1" && pattern="$1"

	showopts="$2"

	_fontlinge_expand || return 0

	# xspec=${1:+"!*.$1"}	# set only if glob passed in as $1
	COMPREPLY=( 
			${COMPREPLY[@]:-} 
			$( compgen $pattern -- "$cur" ) #-X "$xspec"  
			$( test -z "$cur" -a -n "$showopts" && compgen -W "$opts $diropts $fileopts" )
			)

	# workaround for broken (?) complete -o filenames
	test "$pattern" = "-d" -o "$pattern" = "-f"  && for i in  `seq 0 ${#COMPREPLY} ` ; do
		test -d "${COMPREPLY[$i]}" && COMPREPLY[$i]="${COMPREPLY[$i]}/" #|| COMPREPLY[$i]="${COMPREPLY[$i]} "
	done

}

# This function expands tildes in pathnames
#
_fontlinge_expand()
{
	[ "$cur" != "${cur%\\}" ] && cur="$cur\\"

	# expand ~username type directory specifications
	if [[ "$cur" == \~*/* ]]; then
		eval cur=$cur
		
	elif [[ "$cur" == \~* ]]; then
		cur=${cur#\~}
		COMPREPLY=( $( compgen -P '~' -u $cur ) )
		return ${#COMPREPLY[@]}
	fi
}

_fontlinge_complete()
{
	local cur opt command

	local opts diropts fileopts standalone config_options i param
	command="${1//*\/}"

# list of config options in ~/.fontlinge
# one entry per line.
config_options="
mysqlserver
database
username
password
tmp_as_folder
tarpath
fontbase
my_code
sortername
VERSION
HOME
"


# Options for fontlinge_* scripts follow here.
# One option per line.
# Variables:
#     opts         Options like --copy, --move
#     diropts      Options with a directory name, like --fontbase=dirname
#     fileopts     Options with a filename, like --my-code=filename
# IMPORTANT: Some lines have spaces at the end. Don't remove them!


	case "$command" in

		fontlinge_base) ################################################
opts="
--copy 
--move 
--rename-otf 
--previews 
--forcepreviews 
--dbinsert 
--dbkeep 
--look 
--debug 
--verbose 
--percent 
--help 
--my-preview-suffix=
"

diropts="
--fontbase=
"

fileopts="
--my-code=
"

standalone="-d"
			;;

		fontlinge_database_assistant) ######################################
opts="
--check 
--create-user 
--dbadmin-user=
--dbadmin-password=
--download 
--mysqlclient=
--update-database 
--export-text 
--export-my-text 
--import-text 
--overwrite-duplicates 
--trusted-sorters=
--create-database 
--import-database 
--export-database 
--export-my-database 
--phoenix 
--help 
"

diropts="
"

fileopts="
--reject-log=
"
			;;

		fontlinge_montage) #############################################
opts="
--list-fonts 
--list-categories 
--width=
--height=
--order=
--subline-distance=
--subline-fontsize=
--y-gap=
--x-gap=
--x-rgap=
--strokewidth=
--query=
--help 
"

diropts="
"

fileopts="
--my-code=
"
			;;

		fontlinge_getconfig) ###########################################
opts="
--user=
--bash 
--status 
--help 
$config_options
"

diropts="
"

fileopts="
--webgui=
"
			;;


		fontlinge_config) ##############################################
opts="
--file
--help
--webgui-conf
--webgui-path
--change-option
--setperms
$config_options
"

diropts="
"

fileopts="
"
			;;

		*) #############################################################
			echo "_fontlinge_complete: No completion known for $command" >&2
			;;
	esac

	cur=${COMP_WORDS[COMP_CWORD]}

	if [[ "$cur" == --*=*  ]]; then
		opt=${cur%%=*}
		# cut backlash that gets inserted before '=' sign
		opt=${opt%\\*}
		cur=${cur#*=}

		param="-f" # should files or only directories be listed? Default: files, but...
		for i in $diropts ; do # ... here we check if we have to change to -d
			test "$opt=" = "$i" && param="-d"
		done

		_fontlinge_filedir $param
		COMPREPLY=( $( compgen -P "" -W '${COMPREPLY[@]}' -- $cur ))

		return 0
	fi

	if [[ "$cur" == -* ]]; then
		# setting $IFS to have spaces at least after --options with -o nospace
		local IFS=$'\n\t'
		COMPREPLY=( $( echo -e "$opts\n$diropts\n$fileopts" |   \
				   grep "^$cur" ) )
	else
		_fontlinge_filedir "-f" "1"
	fi


}

# -o supported by bash > 2.05a only
nospace=""
[[ ${BASH_VERSINFO[0]} == "2" ]] && [[ ${BASH_VERSINFO[1]} > "05a" ]] && nospace="-o nospace"
[[ ${BASH_VERSINFO[0]} > "2" ]] && nospace="-o nospace"
test -n "$nospace" && dirnames="-o dirnames"
test -n "$nospace" && filenames="-o filenames"

# finally set up autocompletion
complete -F _fontlinge_complete $nospace $dirnames            fontlinge_base
complete -F _fontlinge_complete                    $filenames fontlinge_config
#complete -F _fontlinge_complete $nospace           $filenames fontlinge_database_assistant   # leads to broken autocompletion :-(
complete -F _fontlinge_complete $nospace $dirnames            fontlinge_database_assistant  # does't add trailing / on directories :-(
complete -F _fontlinge_complete $nospace       fontlinge_getconfig
complete -F _fontlinge_complete $nospace       fontlinge_montage

complete -W "--really --verbose --help"        fontlinge_dupe
complete -W "--help --verbose"                 fontlinge_reunion
complete -W "--htmldir --file --help"       -f fontlinge_userinstall

