#/bin/sh

prog="`basename $0`"

usage()
{
	echo "Usage: $prog <enable|disable>"
	exit 1
}

[ $# -eq 1 ] || usage

cmd="$1"
[ "$cmd" = "enable" -o "$cmd" = "disable" ] || usage

root_d="/usr/local/psa"
panel_conf="$root_d/admin/conf/panel.ini"

protocols="TLSv1 TLSv1.1 TLSv1.2"
ciphers="EECDH+AESGCM+AES128:EECDH+AESGCM+AES256:EECDH+CHACHA20:EDH+AESGCM+AES128:EDH+AESGCM+AES256:EDH+CHACHA20"
template="$root_d/admin/conf/templates/custom/domain/nginxDomainVirtualHost.php"

set_config_param()
{
	val="$1"
	param="nginxHttp2"
	section="webserver"

	[ -f "$panel_conf" ] || touch $panel_conf

	# Record exists
	if grep -q "^$param" $panel_conf; then
		sed -i "s|$param.*|$param = $val|" $panel_conf
		return 0
	fi

	# Section does not exists
	if ! grep -q "^\[$section\]" $panel_conf; then
		echo "" >> $panel_conf
		echo "[$section]" >> $panel_conf
		echo "$param = $val" >> $panel_conf
		return 0
	fi

	# Section exists but record doesn't
	sed -ie "s|^\(\[$section\]\)|\1\n$param = $val|" $panel_conf
}

check_openssl_version()
{
	version_str="`openssl version | awk '{print $2}' | sed 's|^\([[:digit:]]*\.[[:digit:]]*\.[[:digit:]]*\).*$|\1|'`"
	version_num="`echo $version_str|awk -F '.' '{print $1$2$3}'`"

	if [ "$version_num" -lt "101" ]; then
		echo "Wrong openssl version. Please install openssl >= 1.0.1 to enable HTTPv2 support."
		return 1
	fi
	return 0
}

check_custom_templates()
{
	if [ -f "$template" ]; then
		echo "WARNING: You are using a custom virtual host template($template)"
		echo "This may cause issues with enabling HTTP/2 support for domains."
	fi
}

check_nginx()
{
	if which rpm >/dev/null 2>&1; then
		str="`rpm -qa|grep sw-nginx`"
		nginx_config="/etc/sysconfig/nginx"
	fi
	if which dpkg >/dev/null 2>&1; then
		str="`dpkg --get-selections sw-nginx | awk '{if ($2 == \"install\") {print $1}}'`"
		nginx_config="/etc/default/nginx"
	fi

	if [ -n "$str" ]; then
		if [ -f "$nginx_config" ]; then
			. $nginx_config
			[ "$NGINX_ENABLED" = "yes" ] && return 0
		fi
		echo "The nginx service is not enabled."
		return 1
	fi

	echo "The nginx service is not installed."
	return 1
}

do_enable()
{
	check_openssl_version || exit 1
	check_custom_templates
	check_nginx || exit 1

	set_config_param "true"
	$root_d/admin/sbin/sslmng -s nginx --custom --ciphers="$ciphers" --protocols="$protocols"
	$root_d/admin/sbin/httpdmng --reconfigure-all
}

do_disable()
{
	set_config_param "false"
	$root_d/admin/sbin/sslmng -s nginx --no-custom
	$root_d/admin/sbin/httpdmng --reconfigure-all
}


case $cmd in
	enable)
		do_enable
	;;
	disable)
		do_disable
	;;
	*)
		usage
	;;
esac

exit 0
