#!/bin/bash

set -e

. "${INSTALLER_DIR}/wizard"

TEMPLATE_SSL="conf/web-ssl"
TEMPLATE_RAW="conf/web-raw"
VHOST_INCLUDES_DIR="/etc/${APP_NAME}/addons/apache2/includes/vhost"
SERVER_INCLUDES_DIR="/etc/${APP_NAME}/addons/apache2/includes/server"
VHOST_CUSTOMIZATION_DIR="/etc/${APP_NAME}/addons/apache2/custom/vhost"
SERVER_CUSTOMIZATION_DIR="/etc/${APP_NAME}/addons/apache2/custom/server"
OSFAMILY="$(wiz_fact osfamily)"
CONF="/etc/${APP_NAME}/conf.d/server"

# remove existing server config files
rm -f ${SERVER_INCLUDES_DIR}/*.conf
mkdir -p "${SERVER_INCLUDES_DIR}"
# remove existing vhost config files
rm -f ${VHOST_INCLUDES_DIR}/*.conf
mkdir -p "${VHOST_INCLUDES_DIR}"
# add customization dirs
mkdir -p "${VHOST_CUSTOMIZATION_DIR}"
mkdir -p "${SERVER_CUSTOMIZATION_DIR}"

enable_apache2_mod() {
	case "$OSFAMILY" in
		"debian"|"suse")
			a2enmod $1
			;;
		"redhat")
			local output="${SERVER_INCLUDES_DIR}/${1}_mod.conf"
			echo "LoadModule ${1}_module modules/mod_${1}.so" > "$output"
			chcon -t httpd_config_t "$output" || true
			;;
	esac
}

enable_apache2_site() {
	local name="$1"
	local tmpfile="$2"
	case "$OSFAMILY" in
		"debian")
			local output="/etc/apache2/sites-available/${name}"
			# starting with ubuntu-14.04, files end in .conf
			if [ -f "$output" ] ; then
				a2dissite "${name}" &>/dev/null || true
				rm -f "$output"
			fi
			mv -f "$tmpfile" "${output}.conf"
			chmod 0640 "${output}.conf"

			a2ensite "${name}.conf"
			;;
		"redhat")
			local output="/etc/httpd/conf.d/${name}.conf"
			mv -f "$tmpfile" "$output"
			chmod 0640 "$output"
			chcon -t httpd_config_t "$output" || true
			;;
		"suse")
			local output="/etc/apache2/vhosts.d/${name}.conf"
			mv -f "$tmpfile" "$output"
			chmod 0640 "$output"
			;;
	esac
}

disable_apache2_site() {
	local name="$1"
	case "$OSFAMILY" in
		"debian")
			if [ -f "/etc/apache2/sites-enabled/$name" ] ; then
				a2dissite "$name" || true
			fi
			if [ -f "/etc/apache2/sites-enabled/${name}.conf" ] ; then
				a2dissite "${name}.conf" || true
			fi
			;;
		"redhat")
			local target="/etc/httpd/conf.d/${name}.conf"
			if [ -f "$target" ] ; then
				cp "$target" "${target}.bak"
				echo "" > "$target"
			fi
			;;
		"suse")
			local target="/etc/apache2/vhosts.d/${name}.conf"
			if [ -f "$target" ] ; then
				cp "$target" "${target}.bak"
				echo "" > "$target"
			fi
			;;
	esac
}

disable_default_apache2_site() {
	# debian
	disable_apache2_site "default"
	disable_apache2_site "000-default"
	# redhat
	disable_apache2_site "welcome"
}

reload_apache2() {
	case "$OSFAMILY" in
		"debian")
			if apache2ctl configtest ; then
				service apache2 restart
			else
				echo "ERROR: apache config check failed. See above."
				exit 2
			fi
			;;
		"suse")
			# apache2ctl is available, but it seems it doesn't work
			service apache2 restart
			;;
		"redhat")
			# make sure the snakeoil certificates are present
			if [ -f /usr/libexec/httpd-ssl-gencerts ]; then
				/usr/libexec/httpd-ssl-gencerts
			fi
			if httpd -t ; then
				service httpd restart
			else
				echo "ERROR: apache config check failed. See above."
				exit 2
			fi
			;;
	esac
}

enable_apache2_vhost_include() {
	local output="$1"
	chmod 0640 "$output"

	if [ "$OSFAMILY" = "redhat" ] ; then
		# deal with SELinux
		chcon -t httpd_config_t "$dst" || true
	fi
}

##
# Cleans and sets the server path prefix from user input.
# Ensures that:
#
#   1. The server prefix always has a trailing slash and leading.
#
#   2. The server prefix is set to '/' when no configuration was made.
#
# Exposes the prefix through SERVER_PATH_PREFIX.
build_server_path_prefix() {
	server_path_prefix="$(wiz_get server/server_path_prefix)"
	local last_server_path_prefix=$(${APP_NAME} config:get SERVER_PATH_PREFIX || echo "/")

	# Remember the last prefix (if any)
	echo "Last prefix was ${last_server_path_prefix}"
	$(${APP_NAME} config:set SERVER_PATH_PREFIX_PREVIOUS="${last_server_path_prefix}")

	# Configure subfolder location
	if [ -z "$server_path_prefix" ]; then
		server_path_prefix="/"
		server_path_prefix_noslash=""
	else
		# Force leading slash if missing
		leading=${server_path_prefix:0:1}
		[[ $leading != "/" ]] && server_path_prefix="/${server_path_prefix}"; :

		# Force trailing slash if missing
		trailing=${server_path_prefix:length-1:1}
		[[ $trailing != "/" ]] && server_path_prefix="${server_path_prefix}/"; :

		server_path_prefix_noslash="$(echo "$server_path_prefix" | sed "s|/$||")"
	fi
}

configure_apache2_server() {
	local web_hostname="$(wiz_get server/hostname)"
	local web_ssl="$(wiz_get server/ssl)"
	local web_ssl_cert="$(wiz_get server/ssl_cert)"
	local web_ssl_key="$(wiz_get server/ssl_key)"
	local web_ssl_ca="$(wiz_get server/ssl_ca)"
	local web_ssl_port="443"
	local web_raw_port="80"
	local web_app_port=$(${APP_NAME} config:get PORT || echo "6000")
	local vhost_includes="compression expiration sys assets"
	local vhost_file=$(mktemp)
	local template="$TEMPLATE_RAW"
	local src
	local dst
	local tmpfile
	local web_protocol="http"
	local web_user="www-data"

	# so that the folder is not empty
	echo "# placeholder, do not remove" > "$SERVER_INCLUDES_DIR/placeholder.conf"

	enable_apache2_mod "rewrite"
	if [ "$server_path_prefix_noslash" != "" ]; then
		vhost_includes="$vhost_includes 00_prefix_redirect"
	fi

	if [ "$OSFAMILY" = "redhat" ] ; then
		web_user="apache"
	elif [ "$OSFAMILY" = "suse" ] ; then
		web_user="wwwrun"
	fi

	if [ "$web_ssl" = "yes" ] ; then
		web_protocol="https"
		template="$TEMPLATE_SSL"
		if [ -z "$web_ssl_ca" ] ; then
			vhost_includes="ssl ${vhost_includes}"
		else
			vhost_includes="ssl ssl_ca ${vhost_includes}"
		fi

		# otherwise port 443 is not open
		if [ "$OSFAMILY" = "suse" ] ; then
			a2enflag SSL
		fi

		enable_apache2_mod "ssl"
		# RHEL 8
		if [ -f /usr/libexec/httpd-ssl-gencerts ]; then
			/usr/libexec/httpd-ssl-gencerts || true
		fi
	fi

	cp -f "$template" "$vhost_file"

	# replace variables
	sed -i "s|_HOSTNAME_|${web_hostname}|g" ${vhost_file}
	sed -i "s|_RAW_PORT_|${web_raw_port}|g" ${vhost_file}
	sed -i "s|_SSL_PORT_|${web_ssl_port}|g" ${vhost_file}
	sed -i "s|_APP_PORT_|${web_app_port}|g" ${vhost_file}
	sed -i "s|openproject|${APP_NAME}|g" ${vhost_file}
	sed -i "s|_SERVER_PATH_PREFIX_NOSLASH_|${server_path_prefix_noslash}|g" ${vhost_file}
	sed -i "s|_SERVER_PATH_PREFIX_|${server_path_prefix}|g" ${vhost_file}

	# remove all previously setup includes
	rm -f ${VHOST_INCLUDES_DIR}/*.conf
	# copy vhost-level includes
	for conf in ${vhost_includes}; do
		tmpfile=$(mktemp)
		src="conf/includes/vhost/${conf}.conf"
		dst="${VHOST_INCLUDES_DIR}/${conf}.conf"
		
		cp -f "$src" "$tmpfile"

		sed -i "s|_SSL_CERT_|${web_ssl_cert}|g" ${tmpfile}
		sed -i "s|_SSL_KEY_|${web_ssl_key}|g" ${tmpfile}
		sed -i "s|_SSL_CA_|${web_ssl_ca}|g" ${tmpfile}
		sed -i "s|openproject|${APP_NAME}|g" ${tmpfile}
		sed -i "s|_SERVER_PATH_PREFIX_NOSLASH_|${server_path_prefix_noslash}|g" ${tmpfile}
		sed -i "s|_SERVER_PATH_PREFIX_|${server_path_prefix}|g" ${tmpfile}

		mv -f "$tmpfile" "$dst"
		enable_apache2_vhost_include "$dst"
	done

	# generate conf file
	web_group="$(id -Gn $web_user | cut -f 1 -d ' ')"
	cat - <<CONF > "$CONF"
export SERVER_HOSTNAME="${web_hostname}"
export SERVER_PROTOCOL="${web_protocol}"
export SERVER_USER="${web_user}"
export SERVER_GROUP="${web_group}"
export SERVER_PATH_PREFIX="${server_path_prefix}"
CONF
	chown ${APP_USER}.${APP_GROUP} "$CONF"

	enable_apache2_mod "proxy"
	enable_apache2_mod "proxy_http"
	enable_apache2_mod "headers"
	enable_apache2_mod "expires"
	enable_apache2_mod "deflate"
	enable_apache2_mod "filter"

	disable_default_apache2_site
	enable_apache2_site "${APP_NAME}" "$vhost_file"
	reload_apache2

}

case "$(wiz_get "server/autoinstall")" in
	"skip")
		;;
	"install")
		build_server_path_prefix
		configure_apache2_server
		;;
	*)
		echo "Unknown value for server/autoinstall"
		;;
esac

exit 0
