#!/bin/bash
#
# ::do_not_edit::
#
# ::copy::
# ::maintainer::
#
CMD=$(basename $0)
CMDVER="1.9"
CMDSTR="$CMD v$CMDVER (2023-08-28)"

set -e -u

usage()
{
	echo "
== $CMDSTR == renew and installs letsencrypt certs ==

usage: $CMD [options]

options:
  -n|--dry-run	don't run anything

  any other certbot-auto option


IMPORTANT NOTES!

  if you pass any certbot-auto option, default options will NOT
  be applied; now the default options are:

    $default_options

  (use   kusa-conf --dump certbot   for details)
" >&2
	exit 1
}


# (MAIN)

cfgfile="$CMD.cfg"
[ -f $cfgfile ] || {
	echo -e "\n$CMD error: config file '$cfgfile' not found" >&2
	exit 1
}
. $cfgfile

F_EXEC=true
DummyTag=
DryRunFlag=
default_options=
webrootsubdir="/docs"
ledir="/etc/letsencrypt"

case ${1:-} in
  -n|--dry-run)
	F_EXEC=false
	DummyTag=" (dummy)"
	DryRunFlag="-n"
	shift
	;;
  -h|--help)
  	usage
	;;
esac

[ $# = 0 ] && default_options="::certbot.options::"

domains_parms=
errors=false

# removes duplicates from domain list
#
dlist="$maindomain"

for dom in $domains
do
	echo -e "$dlist" | grep -q "^$dom$" && continue
	dlist="$dlist\n$dom"
done
domains=$(echo -e "$dlist")

for dom in $domains
do
	dir="$webroot/$dom$webrootsubdir"
	if [ -d "$dir" ]
	then
		domains_parms="$domains_parms\n\t-w $dir -d $dom"
	else
		echo "$CMD error: is not a directory: $dir" >&2
		errors=true
	fi
done
$errors && exit 1

domains_parms=$(echo -e "$domains_parms")

echo "running${DummyTag}:" ./certbot-auto certonly $default_options \
	--email $email \
	--webroot "$domains_parms"

$F_EXEC && {
	./certbot-auto certonly $default_options \
		--email $email \
		--webroot \
		$domains_parms
}


# here we need to disable -e bash flag, because we need the
# error status from jtinstall
#
# using --inform option jtinstall exits with 254 status code
# if any file has been installed (new/modified)
#
set +e
jtinstall $DryRunFlag --inform --input "install-certs" --backup /etc/backup
exitstat=$?
set -e

case $exitstat in
  0)	;; # ok
  254)
  	echo
	echo "FILES NEW OR CHANGED"
	echo
	echo "   remember to reload/restart the related services, ie:"
	echo
	echo "      /etc/init.d/apache2 restart"
	echo "      /etc/init.d/dovecot restart"
	echo "      /etc/init.d/postfix restart"
	echo
	;;
  *)	exit $exitstat
  	;;
esac

exit 0
