#!/bin/sh
# acme.sh pre-hook for certificates of the panel itself: serves www/letsencrypt on port 80 with a small Python
# web server (its PID in tmp/web.pid, a previous one stopped first) and opens port 80 in the firewall there is,
# remembering in tmp/acme.<firewall> that acme_post_hook has to close it again.

MGRDIR=/usr/local/sitemgr

if [ -f ${MGRDIR}/tmp/web.pid ]; then
	pid=$(cat ${MGRDIR}/tmp/web.pid)
	if [ -n "${pid}" ] && ps -p "${pid}" > /dev/null 2>&1; then
		kill ${pid}
	fi
fi

cd ${MGRDIR}/www/letsencrypt || exit 1
python=""
for candidate in python python2 python3; do
	if which ${candidate} > /dev/null 2>&1; then
		python=${candidate}
		break
	fi
done
if [ -z "${python}" ]; then
	# (as the original: the message ends up as the command to run)
	python="Python not found"
fi
${python} ${MGRDIR}/etc/scripts/acme_simple_server &
echo $! > ${MGRDIR}/tmp/web.pid
cat ${MGRDIR}/tmp/web.pid
sleep 2

if which firewall-cmd > /dev/null 2>&1 && service firewalld status > /dev/null; then
	if ! firewall-cmd --list-ports --zone=public | grep -qE '(\s|^)80/tcp($|\s)' \
		&& ! firewall-cmd --list-services --zone=public | grep -qE '(\s|^)http($|\s)'; then
		firewall-cmd --zone=public --add-port 80/tcp && touch ${MGRDIR}/tmp/acme.firewalld
	fi
elif [ -f /sbin/iptables ]; then
	# no check for an existing rule: the post-hook deletes only the first matching one
	iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT && touch ${MGRDIR}/tmp/acme.iptables
elif which nft > /dev/null 2>&1; then
	nft add rule ip filter INPUT tcp dport 80 accept && touch ${MGRDIR}/tmp/acme.nftables
fi
sleep 2
