#!/bin/bash

mkdir -p tmp
BINNAMES=""
BINNAMES=$(find  debian/irstlm/usr/lib/irstlm/bin/ -type f | sed -e 's#^.*/##' -e 's/[.]\(sh\|pl\)$//g' | tr "\n" " ")

cat<<EOF
# Debian GNU/Linux irstlm completion
# Copyright 2013 Giulio Paci <giuliopaci@gmail.com>
# License LGPL-2.1+

_irstlm_get_cmds()
{
    echo "help $BINNAMES";
}

_irstlm()
{
	local cur cmds

	COMPREPLY=()
	cur=\${COMP_WORDS[\$COMP_CWORD]}

	if [ \$COMP_CWORD -eq 1 ]; then
	    cmds="\$(_irstlm_get_cmds)"
	    COMPREPLY=( \$(compgen -o filenames -W "\$cmds" -- \$cur) )
	elif [ \$COMP_CWORD -eq 2 ] && [[ \${COMP_WORDS[1]}  = "help" ]]; then
	    cmds="\$(_irstlm_get_cmds)"
	    COMPREPLY=( \$(compgen -o filenames -W "\$cmds" -- \$cur) )
	elif [ \$COMP_CWORD -ge 2 ] ; then
	    case \${COMP_WORDS[1]} in
EOF

find  debian/irstlm/usr/lib/irstlm/bin/ -type f | while read bin
do
    BINNAME=$(basename "$bin" | sed -e 's/[.]\(sh\|pl\)$//g')
    IRSTLM=debian/irstlm/usr/lib/irstlm/ LD_LIBRARY_PATH=debian/libirstlm0/usr/lib/ "$bin" -h  2>&1 | cat > tmp/"$BINNAME"
    cat tmp/"$BINNAME" | grep "^[[:space:]]*-" | sed -e 's/[(].*//g' -e 's/\([>]\).*/\1/g' -e 's/^[[:space:]]*\|[[:space:]]*$//g' | grep -v '^-h\([[:space:]]\|[[:space:]]*,\)' > tmp/"$BINNAME".preprocess
    awk '(TMP > 0) { print $1 }; /^Parameters:/ { TMP=1 };' tmp/"$BINNAME"  | sed -e 's/^.../-&/' -e 's/^../-&/' -e 's/:.*/=/' | grep -v '^--\?\(Help\|h\)=\?$' >> tmp/"$BINNAME".preprocess

    cat tmp/"$BINNAME".preprocess | sed -e 's/[[:space:]]\+[^<\[[:space:]].*$//g' > tmp/"$BINNAME".preprocess2
    # meld tmp/"$BINNAME".preprocess tmp/"$BINNAME".preprocess2
    COMP_TEXT=$(cat tmp/"$BINNAME".preprocess2 | sed -e 's/[[:space:]]\+.*$//g' -e 's/=.*$/=/g' -e ':repeat; s/^\(-[^|]*\)[|]\([^=]*\)\(=\?\)$/\1\3\n\2\3/g;  t repeat' | tr "\n" " "; echo)

    if test x"$COMP_TEXT" != x
    then
cat<<EOF
	     	"$BINNAME")
			    COMPREPLY=( \$(compgen -o filenames -W "$COMP_TEXT" -- \$cur) )
			    ;;
EOF
    fi
done
cat<<EOF

		*)
		    ;;
	    esac
	fi

	return 0
}

complete -o bashdefault -o default -o nospace -F _irstlm irstlm


# vim:ft=sh:
EOF