#!/bin/bash

# list/ajout/supprime/ un sous-domaine

KAZ_ROOT=$(cd "$(dirname $0)"/..; pwd)
. "${KAZ_ROOT}/bin/.commonFunctions.sh"
setKazVars
. "${DOCKERS_ENV}"

cd "${KAZ_ROOT}"
export PRG="$0"
export IP="127.0.0.1"
export ETC_HOSTS="/etc/hosts"

# no more export in .env
export $(set | grep "domain=")

declare -a forbidenName
forbidenName=(${calcHost} calc ${cloudHost} bureau ${dateHost} date ${dokuwikiHost} dokuwiki ${fileHost} file ${ldapHost} ${pahekoHost} ${gitHost} ${gravHost} ${matterHost} ${officeHost} collabora ${padHost} ${sympaHost} listes ${webmailHost} ${wordpressHost} www ${vigiloHost} form)

export FORCE="NO"
export CMD=""
export SIMU=""

usage(){
    echo "Usage: ${PRG} list [sub-domain...]"
    echo "       ${PRG} [-n] [-f] {add/del} sub-domain..."
    echo "  -h help"
    echo "  -n simulation"
    echo "  -f force protected domain"
    exit 1
}

for ARG in $@
do
    case "${ARG}" in
	'-h' | '-help' )
	    usage
	    ;;
	'-f' )
	    shift
	    export FORCE="YES"
	    ;;
	'-n' )
	    shift
	    export SIMU="echo"
	    ;;
	'list'|'add'|'del' )
	    shift
	    CMD="${ARG}"
	    break
	    ;;
	* )
	    usage
	    ;;
    esac
done

if [ -z "${CMD}" ]; then
    usage
fi

. "${KAZ_KEY_DIR}/env-gandi"

if [[ -z "${GANDI_KEY}" ]] ; then
    echo
    echo "no GANDI_KEY set in ${KAZ_KEY_DIR}/env-gandi"
    usage
fi


waitNet () {
    if [[ "${domain}" = "kaz.local" ]]; then
	return
    fi

    ###  wait when error code 503
    if [[ $(curl -H "authorization: Apikey ${GANDI_KEY}" --connect-timeout 2 -s -D - "${GANDI_API}" -o /dev/null 2>/dev/null | head -n1) != *200* ]]; then
	echo "DNS not available. Please wait..."
	while [[ $(curl -H "authorization: Apikey ${GANDI_KEY}" --connect-timeout 2 -s -D - "${GANDI_API}" -o /dev/null 2>/dev/null | head -n1) != *200* ]]
	do
	    sleep 5
	done
	exit
    fi
}

list(){
    if [[ "${domain}" = "kaz.local" ]]; then
	grep --perl-regex "^${IP}\s.*${domain}" "${ETC_HOSTS}" 2> /dev/null | sed -e "s|^${IP}\s*\([0-9a-z.-]${domain}\)$|\1|g"
	return
    fi
    waitNet
    trap 'rm -f "${TMPFILE}"' EXIT
    TMPFILE="$(mktemp)" || exit 1
    if [[ -n "${SIMU}" ]] ; then
	${SIMU} curl -X GET "${GANDI_API}/records" -H "authorization: Apikey ${GANDI_KEY}"
    else
	curl -X GET "${GANDI_API}/records" -H "authorization: Apikey ${GANDI_KEY}" 2>/dev/null | \
	    sed "s/,{/\n/g" | \
	    sed 's/.*rrset_name":"\([^"]*\)".*rrset_values":\["\([^"]*\)".*/\1:\2/g'| \
	    grep -v '^[_@]'| \
	    grep -e ":${domain}\.*$" -e ":prod[0-9]*$" > ${TMPFILE}
    fi
    if [ $# -lt 1 ]; then
	cat ${TMPFILE}
    else
	for ARG in $@
	do
	    cat ${TMPFILE} | grep "${ARG}.*:"
	done
    fi
}

saveDns () {
    for ARG in $@ ; do
	if [[ "${ARG}" =~ .local$ ]] ; then
	    echo "${PRG}: old fasion style (remove .local at the end)"
	    usage;
	fi
	if [[ "${ARG}" =~ .bzh$ ]] ; then
	    echo "${PRG}: old fasion style (remove .bzh at the end)"
	    usage;
	fi
	if [[ "${ARG}" =~ .dev$ ]] ; then
	    echo "${PRG}: old fasion style (remove .dev at the end)"
	    usage;
	fi
    done
    if [[ "${domain}" = "kaz.local" ]]; then
	return
    fi
    waitNet
    ${SIMU} curl -X POST "${GANDI_API}/snapshots" -H "authorization: Apikey ${GANDI_KEY}" 2>/dev/null
}

badName(){
    [[ -z "$1" ]] && return 0;
    for item in "${forbidenName[@]}"; do
	[[ "${item}" == "$1" ]] && [[ "${FORCE}" == "NO" ]] && return 0
    done
    return 1
}

add(){
    if [ $# -lt 1 ]; then
	exit
    fi
    saveDns $@
    declare -a ADDED
    for ARG in $@
    do
	if badName "${ARG}" ; then
	    echo "can't manage '${ARG}'. Use -f option"
	    continue
	fi
	case "${domain}" in
	    kaz.local )
		if grep -q --perl-regex "^${IP}.*[ \t]${ARG}.${domain}" "${ETC_HOSTS}" 2> /dev/null ; then
		    break
		fi
		if grep -q --perl-regex "^${IP}[ \t]" "${ETC_HOSTS}" 2> /dev/null ; then
		    ${SIMU} sudo sed -i -e "0,/^${IP}[ \t]/s/^\(${IP}[ \t]\)/\1${ARG}.${domain} /g" "${ETC_HOSTS}"
		else
		    ${SIMU} sudo sed -i -e "$ a ${IP}\t${ARG}.${domain}" "${ETC_HOSTS}" 2> /dev/null
		fi
		;;
	    *)
		${SIMU} curl -X POST "${GANDI_API}/records" -H "authorization: Apikey  ${GANDI_KEY}" -H 'content-type: application/json' -d '{"rrset_type":"CNAME", "rrset_name":"'${ARG}'", "rrset_values":["'${site}'"]}'
		echo
		;;
	esac
	ADDED+=("${ARG}")
    done
    echo "Domains added to ${domain}: ${ADDED[@]}"
}

del(){
    if [ $# -lt 1 ]; then
	exit
    fi
    saveDns $@
    declare -a REMOVED
    for ARG in $@
    do
	if badName "${ARG}" ; then
	    echo "can't manage '${ARG}'. Use -f option"
	    continue
	fi
	case "${domain}" in
	    kaz.local )
		if !grep -q --perl-regex "^${IP}.*[ \t]${ARG}.${domain}" "${ETC_HOSTS}" 2> /dev/null ; then
		    break
		fi
		${SIMU} sudo sed -i -e "/^${IP}[ \t]*${ARG}.${domain}[ \t]*$/d" \
			-e "s|^\(${IP}.*\)[ \t]${ARG}.${domain}|\1|g" "${ETC_HOSTS}"
		;;
	    * )
		${SIMU} curl -X DELETE "${GANDI_API}/records/${ARG}" -H "authorization: Apikey ${GANDI_KEY}"
		echo
		;;
	esac
	REMOVED+=("${ARG}")
    done
    echo "Domains removed from ${domain}: ${REMOVED[@]}"
}

#echo "CMD: ${CMD} $*"
${CMD} $*
