#/bin/bash

#koi: gestion des records dns sur AlwaysData 
#ki: fanch&gaël&fab
#kan: 06/04/2025

#doc: https://api.alwaysdata.com/v1/record/doc/
#doc: https://help.alwaysdata.com/fr/api/ 

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=")

#TODO: récupérer la liste des services kaz au lieu des les écrire en dur
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
}

. "${KAZ_KEY_DIR}/env-alwaysdata"
 
if [[ -z "${ALWAYSDATA_TOKEN}" ]] ; then
    echo "no ALWAYSDATA_TOKEN set in ${KAZ_KEY_DIR}/env-alwaysdata"
    usage
fi
 
DOMAIN_ID=$(curl -s -X GET --basic --user "${ALWAYSDATA_TOKEN} account=${ALWAYSDATA_ACCOUNT}:" ${ALWAYSDATA_API}/domain/?name=${domain} | jq '.[0].id')

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

list(){
  TARGET=$@
  LISTE=$(curl -s -X GET --basic --user "${ALWAYSDATA_TOKEN} account=${ALWAYSDATA_ACCOUNT}:" "${ALWAYSDATA_API}/record/?domain=${DOMAIN_ID}&type=CNAME&name=${TARGET}" | jq '.[] | "\(.name):\(.value)"')
  echo ${LISTE}
}

saveDns () {
  mkdir -p /root/dns
  ${SIMU} curl -s -X GET --basic --user "${ALWAYSDATA_TOKEN} account=${ALWAYSDATA_ACCOUNT}:" "${ALWAYSDATA_API}/record/?domain=${DOMAIN_ID}" -o /root/dns/dns_save_$(date +'%Y%m%d%H%M%S')
}

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
        ${SIMU} curl -s -X POST -d "{\"domain\":\"${DOMAIN_ID}\", \"type\":\"CNAME\", \"name\":\"${ARG}\", \"value\":\"${site}.${domain}\"}" --basic --user "${ALWAYSDATA_TOKEN} account=${ALWAYSDATA_ACCOUNT}:" "${ALWAYSDATA_API}/record/"
	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
	RECORD_ID=$(curl -s -X GET --basic --user "${ALWAYSDATA_TOKEN} account=${ALWAYSDATA_ACCOUNT}:" "${ALWAYSDATA_API}/record/?name=${ARG}&type=CNAME&domain=${DOMAIN_ID}" | jq ".[] | select(.name==\"${ARG}\").id")
	${SIMU} curl -s -X DELETE --basic --user "${ALWAYSDATA_TOKEN} account=${ALWAYSDATA_ACCOUNT}:" "${ALWAYSDATA_API}/record/${RECORD_ID}/"
	REMOVED+=("${ARG}")
    done
    echo "Domains removed from ${domain}: ${REMOVED[@]}"
}

${CMD} $*
