#!/bin/bash

CNF=/etc/sys-ssl.conf
SDT=/etc/dehydrated/sysadmin/domains.txt

if [ -f $CNF ]; then
	. $CNF
else
	echo "ERROR: $CNF not found"
	exit 11
fi

if [ -z "$domain" ]; then
	echo "ERROR: no primary domain defined"
	exit 11
fi

newdt=""
NL=$'\n'

firstcrt=1
for cert in $certs; do

	certhosts="d_${cert}"

	if [ -n "${!certhosts}" ]; then

		if [ $firstcrt -gt 1 ]; then
			newdt="${newdt}${NL}"
		fi
		firstcrt=2

		first=1
		for host in ${!certhosts}; do
			if [ $first -eq 1 ]; then
				newdt="${newdt}${host}.${domain}"
				first=2
			else
				newdt="${newdt} ${host}.${domain}"
			fi
		done
	else
		echo "WARNING: No hostnames defined for ${cert}"
	fi
done

if [ -f $SDT ]; then
	olddt=`cat $SDT`
else
	olddt=""
fi

newdt_s=`echo "$newdt" | sort | uniq`

if [ "$olddt" != "$newdt_s" ]; then
	echo "${newdt_s}" > $SDT
	echo "domains.txt changed"
	exit 1
else
	echo "no change in domains.txt"
	exit 0
fi
