#!/bin/bash

set -u

. driglibash-base

# For some variables
. /etc/jeancloud.env

# Test secret presence
[ ! -f "$DATA_DIR/rfc2136.ini" ] && echo "$0 Missing file '$DATA_DIR/rfc2136.ini'" && exit 1

export workdir="$(mktemp -d)"
mkdir -p "$workdir/{work,logs}"


echo "Renew existing certs"
certbot renew --config-dir "$DATA_DIR/certs" --logs-dir "$workdir/logs" --dns-rfc2136 --dns-rfc2136-credentials "$DATA_DIR/rfc2136.ini" --work-dir "$workdir" || true

echo "For each service, read all possible domains"
while IFS=';' read -r id username service target ; do
	if [ -z "$service" ] ; then continue ; fi

	if [ -d "$DATA_DIR/certs/live/$service" ] ; then
		#echo "Already exists, thats a job for renew : $service"
		continue
	fi

	# acme
	"$DOCKER_DIR/acme-dns.sh" "$service" "$workdir"

done < <(grep -v '^#' "$servicefile")

echo "Push certs to other servers"
for srv in $(host -t TXT shlago.jean-cloud.org ns.jean-cloud.org | grep -Po 'descriptive text "\K[^"]+' | tr ',' ' ' | tr ' ' '\n') nougaro tetede montbonnot max raku izzo ; do
	server="$srv.jean-cloud.org"
	[ -n "$(grep "$server" /etc/hosts)" ] && continue
	echo "-- $server"
	rsync -avz -e "ssh -i '$DATA_DIR/certs.priv' -p 45985" "$DATA_DIR/certs" "certs@$server:$DATA_DIR/" || true
done
