#!/bin/bash

# Check that mod_md can create and use its default store directory
# (/var/lib/apache2/md, set by mods-available/md.conf) when apache2 runs under
# systemd with its sandboxing (ProtectSystem=full makes /etc read-only, which is
# why the upstream default of /etc/apache2/md does not work).
#
# This needs no domain and no network: mod_md creates and chowns its store on
# every start, even if no MDomain is configured.
#
# The files that httpd child processes write at certificate renewal time
# (challenges/, staging/, ocsp/) are the ones that can silently break and only
# show up months later, so also check that the worker user can actually write
# there. The renewal itself is exercised by the md-acme test.
set -eu

STORE=/etc/apache2/md

fail () {
	echo "FAIL: $@" >&2
    exit 1
}

# APACHE_RUN_USER, as configured in /etc/apache2/envvars
RUN_USER=$(set +eu; . /etc/apache2/envvars >/dev/null 2>&1; echo "${APACHE_RUN_USER:-www-data}")

cleanup() {
	status=$?
	set +e
	if [ "$status" -ne 0 ]; then
        echo "## Something failed, gathering logs"
        echo
        echo "### apache2 status"
		systemctl status apache2.service
        echo
        echo "### apache2 error.log"
		cat /var/log/apache2/error.log
        echo
        echo "### $(dirname $STORE)"
        ls -la $(dirname "${STORE}") "${STORE}"
        echo
        echo "### modules, confs, sites"
        ls -la /etc/apache2/mods-enabled/ /etc/apache2/conf-enabled /etc/apache2/sites-enabled/
	fi
	a2dismod -q md
	systemctl restart apache2
}

trap cleanup EXIT

owner () {
	stat -c '%U' "$1"
}

override_systemd_throttling() {
    local svc="${1}"

    mkdir -p "/run/systemd/system/${svc}.service.d"
    cat > "/run/systemd/system/${svc}.service.d/override.conf" <<EOF
[Unit]
StartLimitIntervalSec=0
EOF
    systemctl daemon-reload
}

check_store () {
    echo "### Checking $STORE"
	[ -d "$STORE" ] || { fail "$STORE does not exist"; return; }
	[ -f "$STORE/md_store.json" ] || fail "$STORE/md_store.json is missing"
	[ "$(owner "$STORE")" = root ] || fail "$STORE is not owned by root"

	for d in challenges staging accounts ocsp; do
		[ -d "$STORE/$d" ] || fail "$STORE/$d does not exist"
	done

	# directories written to by the (unprivileged) worker processes
	for d in challenges staging ocsp; do
		o=$(owner "$STORE/$d")
		[ "$o" = "$RUN_USER" ] || fail "$STORE/$d is owned by $o, expected $RUN_USER"
		runuser -u "$RUN_USER" -- touch "$STORE/$d/.write-test" || fail "$RUN_USER cannot write to $STORE/$d"
		rm -f "$STORE/$d/.write-test"
	done

	# the worker user must not be able to modify the store itself
	if runuser -u "$RUN_USER" -- touch "$STORE/.write-test" 2>/dev/null; then
		rm -f "$STORE/.write-test"
		fail "$RUN_USER can write to $STORE"
	fi
}

check_service () {
    echo "### Checking apache2 service"
	systemctl is-active --quiet apache2 || fail "apache2 is not active"
	# AH10046/AH10047: store/challenges setup, AH10072: registry setup
	if grep -E "AH100(46|47|72)" /var/log/apache2/error.log; then
		fail "mod_md store errors in error.log"
	fi
}

override_systemd_throttling apache2

echo
echo "## Fresh install"
echo "### Enabling mod_md"
a2enmod md
echo "### Apache config test"
apachectl configtest
echo "### Restarting apache"
systemctl restart apache2
check_service
check_store

echo
echo "## Existing store, restart and reload"
echo "### Restarting"
systemctl restart apache2
check_service
check_store
echo "### Reloading"
systemctl reload apache2
check_service
check_store

echo
echo "## Wrong ownership is repaired"
chown -R root:root "$STORE/challenges" "$STORE/staging" "$STORE/ocsp"
echo "### Restarting"
systemctl restart apache2
check_service
check_store

