#!/bin/sh

get_python() {
    if which python >/dev/null 2>&1 ; then
        echo python
    elif which python2 >/dev/null 2>&1 ; then
        echo python2
    elif which python3 >/dev/null 2>&1 ; then
        echo python3
    else
        echo "Python not found"
        exit 1
    fi
}

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

cd /usr/local/mgr5/www/letsencrypt || exit 1
PYTHON=$(get_python)
${PYTHON} /usr/local/mgr5/etc/scripts/acme_simple_server &
echo $! > /usr/local/mgr5/tmp/web.pid
cat /usr/local/mgr5/tmp/web.pid
sleep 2

if which firewall-cmd >/dev/null 2>&1 && service firewalld status >/dev/null ; then
	# Check if http port is open
	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 /usr/local/mgr5/tmp/acme.firewalld
	fi
elif [ -f /sbin/iptables ]; then
	# Do not need check if open because deletion delete only first rule
        iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT && touch /usr/local/mgr5/tmp/acme.iptables
fi
sleep 2
