#!/bin/bash

# list/ajout/supprime/ les domaines extérieurs à kaz.bzh

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

export PRG="$0"
cd $(dirname $0)

. "${DOCKERS_ENV}"

LETS_DIR="/etc/letsencrypt/$([ "${mode}" == "local" ] && echo "local" || echo "live")"

declare -a availableComposes availableOrga
availableComposes=(${pahekoHost} ${cloudHost} ${dokuwikiHost} ${wordpressHost} ${matterHost} ${castopodHost})
availableOrga=($(sed -e "s/\(.*\)[ \t]*#.*$/\1/" -e "s/^[ \t]*\(.*\)-orga$/\1/" -e "/^$/d" "${KAZ_CONF_DIR}/container-orga.list"))
availableProxyComposes=($(getList "${KAZ_CONF_DIR}/container-proxy.list"))

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

export CMD=""
export SIMU=""
export CHANGE=""

usage(){
    echo "Usage: ${PRG} list [friend-domain...]"
    echo "       ${PRG} [-n] add orga [${pahekoHost} ${cloudHost} ${dokuwikiHost} ${wordpressHost} ${matterHost} ${castopodHost}] [friend-domain...] "
    echo "       ${PRG} [-n] del [friend-domain...]"
    echo "       ${PRG} -l"
    echo "  -l short list"
    echo "  -renewAll"
    echo "  -h help"
    echo "  -n simulation"
    exit 1
}

export CERT_CFG="${KAZ_CONF_PROXY_DIR}/foreign-certificate"

createCert () {
    (
	fileName="${LETS_DIR}/$1-key.pem"
	#[ -f "${fileName}" ] || return
	# if [ -f "${fileName}" ]; then
	#     fileTime=$(stat --format='%Y' "${fileName}")
	#     current_time=$(date +%s)
	#     if (( "${fileTime}" > ( "${current_time}" - ( 60 * 60 * 24 * 89 ) ) )); then
	# 	exit
	#     fi
	# fi
	printKazMsg "create certificat for $1"
	${SIMU} docker exec -i proxyServ bash -c "/opt/certbot/bin/certbot certonly -n --nginx -d $1"
    )

}

for ARG in $@; do
    case "${ARG}" in
	'-h' | '-help' )
	    usage
	    ;;
	'-n' )
	    shift
	    export SIMU="echo"
	    ;;
	'-renewAll')
	    for i in $("${KAZ_BIN_DIR}/foreign-domain.sh" -l); do
		echo "$i"
		createCert "$i" |grep failed
	    done
	    exit
	    ;;
	'-l')
	    for compose in ${availableComposes[@]} ; do
		grep "server_name" "${KAZ_CONF_PROXY_DIR}/${compose}_kaz_name" | sed -e "s/[ \t]*\([^#]*\)#.*/\1/g" -e "/^$/d" -e "s/.*server_name[ \t]\([^ ;]*\).*/\1/"
	    done
	    exit
	    ;;
	'list'|'add'|'del' )
	    shift
	    CMD="${ARG}"
	    break
	    ;;
	* )
	    usage
	    ;;
    esac
done

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

########################################
badDomaine () {
    [[ -z "$1" ]] && return 0;
    [[ ! "$1" =~ ^[-.a-zA-Z0-9]*$ ]] && return 0;
    return 1
}
badOrga () {
    [[ -z "$1" ]] && return 0;
    [[ ! " ${availableOrga[*]} " =~ " $1 " ]] && return 0
    return 1
}
badCompose () {
    [[ -z "$1" ]] && return 0;
    [[ ! " ${availableComposes[*]} " =~ " $1 " ]] && return 0
    return 1
}

########################################
listServ () {
    for compose in ${availableComposes[@]} ; do
	sed -e "s/[ \t]*\([^#]*\)#.*/\1/g" -e "/^$/d" -e "s/.*server_name[ \t]\([^ ;]*\).*/\1 : ${compose}/" "${KAZ_CONF_PROXY_DIR}/${compose}_kaz_name"
    done
}

listOrgaServ () {
    for compose in ${availableComposes[@]} ; do
	sed -e "s/[ \t]*\([^#]*\)#.*/\1/g" -e "/^$/d" -e "s/\([^ ]*\)[ \t]*\([^ \t;]*\).*/\1 => \2 : ${compose}/" "${KAZ_CONF_PROXY_DIR}/${compose}_kaz_map"
    done
}

########################################
list () {
    previousOrga=$(listOrgaServ)
    previousServ=$(listServ)
    if [ $# -lt 1 ]; then
	[ -n "${previousOrga}" ] && echo "${previousOrga}"
	[ -n "${previousServ}" ] && echo "${previousServ}"
	return
    fi
    for ARG in $@
    do
	orga=$(echo "${previousOrga}" | grep "${ARG}.* =>")
	serv=$(echo "${previousServ}" | grep "${ARG}.* =>")
	[ -n "${orga}" ] && echo "${orga}"
	[ -n "${serv}" ] && echo "${serv}"
    done
}

########################################
add () {
    # $1 : orga
    # $2 : service
    # $3 : friend-domain
    [ $# -lt 3 ] && usage
    badOrga $1 && echo "bad orga: ${RED}$1${NC} not in ${GREEN}${availableOrga[@]}${NC}" && usage
    badCompose $2 && echo "bad compose: ${RED}$2${NC} not in ${GREEN}${availableComposes[@]}${NC}" && usage
    ORGA=$1
    COMPOSE=$2
    shift; shift
    CLOUD_SERVNAME="${ORGA}-${nextcloudServName}"
    CLOUD_CONFIG="${DOCK_VOL}/orga_${ORGA}-cloudConfig/_data/config.php"

    # XXX check compose exist in orga ?
    # /kaz/bin/kazList.sh service enable ${ORGA}
    if [ "${COMPOSE}" = "${cloudHost}" ]; then
	if ! [[ "$(docker ps -f name=${CLOUD_SERVNAME} | grep -w ${CLOUD_SERVNAME})" ]]; then
	    printKazError "${CLOUD_SERVNAME} not running... abort"
	    exit
	fi
    fi

    for FRIEND in $@; do
	badDomaine "${FRIEND}"  && echo "bad domaine: ${RED}${FRIEND}${NC}" && usage
    done

    for FRIEND in $@; do
	createCert "${FRIEND}"
	if [ "${COMPOSE}" = "${cloudHost}" ]; then
	    IDX=$(awk  'BEGIN {flag=0; cpt=0} /trusted_domains/ {flag=1} /)/ {if (flag) {print cpt+1; exit 0}} / => / {if (flag && cpt<$1) cpt=$1}' "${CLOUD_CONFIG}")
	    ${SIMU} docker exec -ti -u 33 "${CLOUD_SERVNAME}" /var/www/html/occ config:system:set trusted_domains "${IDX}" --value="${FRIEND}"
	fi
	
	previousOrga=$(listOrgaServ | grep "${FRIEND}")
	[[ " ${previousOrga}" =~ " ${FRIEND} => ${ORGA} : ${COMPOSE}" ]] && echo "  - already done" && continue
	[[ " ${previousOrga}" =~ " ${FRIEND} " ]] && echo "  - ${YELLOW}${BOLD}$(echo "${previousOrga}" | grep -e "${FRIEND}")${NC} must be deleted before" && return
	if [[ -n "${SIMU}" ]] ; then
	    echo "${FRIEND} ${ORGA}; => ${KAZ_CONF_PROXY_DIR}/${COMPOSE}_kaz_map"
	    cat <<EOF
    => ${KAZ_CONF_PROXY_DIR}/${COMPOSE}_kaz_name
server_name ${FRIEND};
EOF
	else
	    echo "${FRIEND} ${ORGA};" >> "${KAZ_CONF_PROXY_DIR}/${COMPOSE}_kaz_map"
	    cat  >> "${KAZ_CONF_PROXY_DIR}/${COMPOSE}_kaz_name" <<EOF
server_name ${FRIEND};
EOF
	fi
	echo "${PRG}: ${FRIEND} added"
	
	CHANGE="add"
    done
    #(cd "${KAZ_COMP_DIR}/${ORGA}-orga"; docker-compose restart)
}

########################################
del () {
    [ $# -lt 1 ] && usage

    for FRIEND in $@; do
	badDomaine "${FRIEND}"  && echo "bad domaine: ${RED}${FRIEND}${NC}" && usage
	previous=$(listOrgaServ | grep -e "${FRIEND}")
	[[ ! "${previous}" =~ ^${FRIEND} ]] && echo "${FRIEND} not found in ${previous}" && continue
	# XXX if done OK
	for COMPOSE in ${availableComposes[@]} ; do
	    if grep -q -e "^[ \t]*${FRIEND}[ \t]" "${KAZ_CONF_PROXY_DIR}/${COMPOSE}_kaz_map" ; then
		if [ "${COMPOSE}" = "${cloudHost}" ]; then
		    ORGA="$(grep "${FRIEND}" "${KAZ_CONF_PROXY_DIR}/${COMPOSE}_kaz_map" | sed "s/^${FRIEND}\s*\([^;]*\);/\1/")"
		    CLOUD_CONFIG="${DOCK_VOL}/orga_${ORGA}-cloudConfig/_data/config.php"
		    ${SIMU} sed -e "/\d*\s*=>\s*'${FRIEND}'/d" -i "${CLOUD_CONFIG}"
		fi
		${SIMU} sed -e "/^[ \t]*${FRIEND}[ \t]/d" -i "${KAZ_CONF_PROXY_DIR}/${COMPOSE}_kaz_map"
	    fi
	    if grep -q -e "^[ \t]*server_name ${FRIEND};" "${KAZ_CONF_PROXY_DIR}/${COMPOSE}_kaz_name" ; then
		${SIMU} sed -i "${KAZ_CONF_PROXY_DIR}/${COMPOSE}_kaz_name" \
			-e "/^[ \t]*server_name ${FRIEND};/d"
	    fi
	done
	echo "${PRG}: ${FRIEND} deleted"
	CHANGE="del"
    done
}

########################################
${CMD} $@

if [ -n "${CHANGE}" ] ; then
    echo "Reload proxy conf"
	for item in "${availableProxyComposes[@]}"; do
    	${SIMU} ${KAZ_COMP_DIR}/${item}/proxy-gen.sh
    	${SIMU} "${KAZ_COMP_DIR}/proxy/reload.sh"
    done
fi

########################################
