#/usr/bin/env bash

_foreign_domain_completions () {
    KAZ_ROOT=$(cd "$(dirname ${COMP_WORDS[0]})"/..; pwd)
    . "${KAZ_ROOT}/bin/.commonFunctions.sh"
    setKazVars

    COMPREPLY=()
    local cword=${COMP_CWORD} cur=${COMP_WORDS[COMP_CWORD]} card=${#COMP_WORDS[@]} i w skip=0
    for ((i=1 ; i<cword; i++)) ; do
	w="${COMP_WORDS[i]}"
        [[ "${w}" == -* ]] && ((skip++))
    done
    local arg_pos w i cmd= opt1= opt2=
    ((arg_pos = cword - skip))
    for ((i=1 ; i<card; i++)) ; do
	w="${COMP_WORDS[i]}"
	if [ -z "${cmd}" ] ; then
	    [[ "${w}" == -* ]] || cmd="${w}"
	    continue
	fi
	if [ -z "${opt1}" ] ; then
	    [[ "${w}" == -* ]] || opt1="${w}"
	    continue
	fi
	if [ -z "${opt2}" ] ; then
	    [[ "${w}" == -* ]] || opt2="${w}"
	    break
	fi
    done

    case "$cur" in
	-*)
	    COMPREPLY=( $(compgen -W "-h -n" -- "${cur}" ) ) ;;
	*)
	    local cmd_available="list add del"
	    if [ "${arg_pos}" == 1 ]; then
		# $1 of foreign-domain.sh .sh
		COMPREPLY=($(compgen -W "${cmd_available}" -- "${cur}"))
	    else
		. "${KAZ_CONF_DIR}/dockers.env"
		case "${cmd}" in
		    
		    "list")
		    ;;
		    "add")
			case "${arg_pos}" in
			    2)
				declare -a availableOrga
				availableOrga=($(sed -e "s/\(.*\)[ \t]*#.*$/\1/" -e "s/^[ \t]*\(.*\)-orga$/\1/" -e "/^$/d" "${KAZ_CONF_DIR}/container-orga.list"))
				COMPREPLY=($(compgen -W "${availableOrga[*]}" -- "${cur}"))
				;;
			    3)
				local availableComposes=$(${KAZ_COMP_DIR}/${opt1}-orga/orga-gen.sh -l)
				COMPREPLY=($(compgen -W "${availableComposes[*]}" -- "${cur}"))
				;;
			esac
			;;
		    "del")
			case "${arg_pos}" in
			    1)
				;;
			    *)
				local availableComposes=$(${KAZ_BIN_DIR}/kazList.sh service validate|sed -e "s/\bcollabora\b//" -e "s/  / /")
				declare -a availableDomaine
				availableDomaine=($(for compose in ${availableComposes[@]} ; do
							sed -e "s/[ \t]*\([^#]*\)#.*/\1/g" -e "/^$/d" -e "s/.*server_name[ \t]\([^ ;]*\).*/\1/" "${KAZ_CONF_PROXY_DIR}/${compose}_kaz_name"
						    done))
				COMPREPLY=($(compgen -W "${availableDomaine[*]}" -- "${cur}"))
				;;
			esac
			;;
		esac
	    fi
	    ;;
    esac
    return 0
}
complete -F _foreign_domain_completions foreign-domain.sh