#!/bin/bash

. ${TOOLKIT}-functions.sh

options=$(jtconf certbot.options 2>/dev/null) || :

# just a bunch of required packages very specific to
# certbot-auto script, if not installed we need to run
# the setup process
#
needed_pkgs="
	python-virtualenv
	augeas-lenses
	libaugeas0
"

# on first run needs to configure python env, but Devuan is
# not supported and certbot-auto cannot bootstrap
#
needs_setup=false

for pkg in $needed_pkgs
do
	is_installed $pkg || {
		needs_setup=true
		break
	}
done

eval $(grep '^LE_AUTO_VERSION=' /etc/ssl/certbot-auto) || exit $?


$needs_setup && {
	# since Devuan is a Debian derivate, we fool certbot a bit ...
	#
	temp_debian_release=false

	[ -f /etc/debian_release ] && {
		cd /etc
		rm -f debian_release
		ln -s devuan_release debian_release
		temp_debian_release=true
	}
	cd /etc/ssl
	echo -n "  certbot-auto $LE_AUTO_VERSION env setup: "
	./certbot-auto --os-packages-only --no-self-update

	$temp_debian_release && rm -f /etc/debian_release
}


echo "  certbot-auto: installed version $LE_AUTO_VERSION with options $options"


# cleanup old/broken files
#
remove="
	/etc/ssl/new-certbot.sh 
	/etc/ssl/certbot-new.sh
	/etc/ssl/install
	/etc/cron.monthly/certbot-renew.cron
"
case $(jtconf certbot.cron_frequency) in
  daily)	remove="$remove /etc/cron.weekly/certbot-renew /etc/cron.monthly/certbot-renew" ;;
  weekly)	remove="$remove /etc/cron.daily/certbot-renew /etc/cron.monthly/certbot-renew" ;;
  monthly)	remove="$remove /etc/cron.daily/certbot-renew /etc/cron.weekly/certbot-renew" ;;
esac

uninstallfiles $remove
purgefiles $remove



#$SOMETHING_CHANGED && {
	# ...
#}

exit 0
