#!/bin/sh
#
# Post installation script for Tomcat
#

set -e

TOMCAT_USER="tomcat"
TOMCAT_GROUP="tomcat"

CONFFILES="tomcat-users.xml web.xml server.xml logging.properties context.xml catalina.properties jaspic-providers.xml"

case "$1" in
    configure)
	# Create the tomcat user as defined in /usr/lib/sysusers.d/tomcat10.conf
	systemd-sysusers

	# Install the configuration files
	for conffile in $CONFFILES;
	do
		ucf --debconf-ok --three-way /usr/share/tomcat10/etc/$conffile /etc/tomcat10/$conffile

		# Configuration files should not be modifiable by the tomcat user, as this can be
		# a security issue (an attacker may insert code in a webapp and rewrite the tomcat
		# configuration) but those files should be readable by tomcat, so we set the group
		# to tomcat.
		if [ -f "/etc/tomcat10/$conffile" ]; then
			chown root:$TOMCAT_GROUP /etc/tomcat10/$conffile
			chmod 640 /etc/tomcat10/$conffile
		fi
	done

	# Install /etc/logrotate.d/tomcat10
	ucf --debconf-ok --three-way /usr/share/tomcat10/logrotate.template /etc/logrotate.d/tomcat10

	# Install /etc/default/tomcat10
	ucf --debconf-ok --three-way /usr/share/tomcat10/default.template /etc/default/tomcat10

	# Install the policy files for the security manager. These files should not be modifiable
	# by the tomcat user. Only diverge from default permissions for known Debian files.
	chown root:$TOMCAT_GROUP /etc/tomcat10/policy.d
	for policyfile in 01system.policy 02debian.policy 03catalina.policy 04webapps.policy 50local.policy;
	do
		if [ -f "/etc/tomcat10/policy.d/$policyfile" ]; then
			chown root:$TOMCAT_GROUP /etc/tomcat10/policy.d/$policyfile
			chmod 640 /etc/tomcat10/policy.d/$policyfile
		fi
	done

	# Grant the tomcat group read/write access to /var/lib/tomcat10/lib. This allows
	# a non-root administrator in the tomcat group to add jar files to the classpath
	# (for example database drivers).
	chown -Rh $TOMCAT_USER:$TOMCAT_GROUP /var/lib/tomcat10/lib

	# Grant the tomcat group read/write access to the /etc/tomcat10/Catalina directory
	# to write the hosts/contexts configuration files.
	chown -Rh root:$TOMCAT_GROUP /etc/tomcat10/Catalina
	chmod 775 /etc/tomcat10/Catalina

	# Grant read/write access to tomcat to the webapps directory (needed for extracting
	# war files and for deploying webapps by non-root administrators in the tomcat group).
	chown -Rh $TOMCAT_USER:$TOMCAT_GROUP /var/lib/tomcat10/webapps
	chmod 775 /var/lib/tomcat10/webapps

	# Grant read/write access to tomcat to the log and cache directories
	chown -Rh $TOMCAT_USER:adm /var/log/tomcat10/
	chmod 2770 /var/log/tomcat10/
	chown -Rh $TOMCAT_USER:$TOMCAT_GROUP /var/cache/tomcat10/
	chmod 750 /var/cache/tomcat10/
    ;;
esac

# Install the default root webapp if there isn't one already
if [ ! -d /var/lib/tomcat10/webapps/ROOT ]; then
    cp -r /usr/share/tomcat10-root/default_root /var/lib/tomcat10/webapps/ROOT
fi

#DEBHELPER#
