#!/bin/bash

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

cd $(dirname $0)

PWD=$(pwd)
ORGA_DIR=$(basename ${PWD})
availableProxyComposes=($(getList "${KAZ_CONF_DIR}/container-proxy.list"))
TMPL_PROXY_COMPOSES=()
for item in "${availableProxyComposes[@]}"; do
	TMPL_PROXY_COMPOSES+=("${KAZ_COMP_DIR}/${item}/docker-compose.tmpl.yml")
done
ORGA_LIST="${KAZ_CONF_DIR}/container-orga.list"

remove () {
    while : ; do
    read -r -p "Are you sure remove ${ORGA}? [y/N] " response
    case "$response" in
	[oO][uU][iI] | [yY][eE][sS] | [yY] | [oO] )

	    echo "remove ${ORGA}"
	    . .env
	    ORGA_FLAG=${ORGA//-/_}_orga
		for item in "${TMPL_PROXY_COMPOSES[@]}"; do
			echo "Update ${item}"
			if grep -q "^{{${ORGA_FLAG}" "${item}" 2> /dev/null ; then
			sed -i -e "/^{{${ORGA_FLAG}/,/^}}/d" "${item}"
			fi
		done
	    DEL_DOMAIN=""
	    for serv in ${pahekoHost} ${cloudHost} ${officeHost} ${dokuwikiHost} ${wordpressHost} ${matterHost}
	    do
	     	DEL_DOMAIN+="${ORGA}-${serv} "
	    done
	    ${KAZ_BIN_DIR}/dns.sh del ${DEL_DOMAIN}
	    ${KAZ_BIN_DIR}/container.sh stop ${ORGA}-orga
	    sed -i -e "/proxy_${ORGA_FLAG}=/d" "${DOCKERS_ENV}"
	    sed -i -e "/^${ORGA}-orga$/d" "${ORGA_LIST}"
	    rm -fr "${KAZ_COMP_DIR}/${ORGA}-orga"
		
	    rm -fr "${KAZ_KEY_DIR}/orgas/${ORGA}"
	    exit;;
	    [Nn]* )

	    exit;;
            * )

		echo "Please answer yes or no."
		;;
    esac
    done
}

if [[ "${ORGA_DIR}" = "orgaTmpl" ]]
then
    while :
    do
	echo -n "Give new organization name ? "
	read ORGA
	[[ "${ORGA}" =~ ^[a-zA-Z0-9_\-]+$ ]] && [[ ! -z "${ORGA}" ]] && break
	echo "Name must contains only a-zA-Z0-9_\-"
    done
    remove
    exit
fi

if [[ "${ORGA_DIR}" != *"-orga" ]]
then
    echo "it's not an orga dir"
    exit
fi

ORGA=${ORGA_DIR%-orga}
remove
