#!/bin/sh
# apache2postrotate v1.0.4  (c) 21.6.2012 by Andreas Ley  (u) 6.3.2026
# Common tasks after apache2 logrotate

# FIXME: Do we need to set APACHE_LOG_DIR? A non-runnig server produces
# [Mon Jan 06 11:58:23 2014] [error] (2)No such file or directory: could not open transfer log file /var/www/user/209989/44569/${APACHE_LOG_DIR}/other_vhosts_access.log.
# Unable to open logs
# perhaps when trying to start due to reload operations?

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
export PATH

umask 022

mkdir -p /var/www/log ###
# If we don't do this, myaccesslog finds this directory and dies :-(
test -x /usr/bin/myaccesslog && chgrp --reference=/usr/bin/myaccesslog /var/www/log ###
# Must be this open for run_awstats to descend to its log directory
chmod 755 /var/www/log ###

# DEBUG
mkdir -p /var/www/log/apache2postrotate && chown 0:9998 /var/www/log/apache2postrotate && chmod 750 /var/www/log/apache2postrotate && exec >/var/www/log/apache2postrotate/$$.out 2>/var/www/log/apache2postrotate/$$.err && set -x && printenv >/var/www/log/apache2postrotate/$$.env && find /var/www/log/apache2postrotate -mtime +7 -delete

MAILADDR="apache@scc.kit.edu"

usage()
{
	echo "Usage: `basename $0` [-v] [-u uid:gid] fqdn [...]" >&2
	echo "-v  verbose mode" >&2
	echo "-u  handle user instance" >&2
	exit 1
}

set -- `getopt hxvu: $*` || usage

trace=false
verbose=false
while :; do
	case $1 in
		-h)	sed '1d;s/^# *//;/^$/q' $0; usage;;
		-x)	set -x; trace=true; shift;;
		-v)	verbose=true; shift;;
		-u)	uid="${2%:*}"; gid="${2#*:}"; shift 2;;
		--)	shift; break;;
	esac
done

test $# -lt 1 && usage

# First check for new certificate, so the certificate can be loaded with the
# following graceful restart
# This was great when we had certificates running 3 years or with http-01 which handles this in 30 seconds, but with dns-01 and sequential logrotate, this isn't possible any more
#ssl_check "$@"

# Restart the server to re-open log files and load certificates
if test -n "${uid}" -a \( -f "/var/www/user/${uid}:${gid}/run/httpd.pid" -o -f "/run/httpd/${uid}:${gid}/httpd.pid" \); then
	# FIXME: Should we run systemctl reload httpd@${uid}:${gid} ?
	pid=`cat "/var/www/user/${uid}:${gid}/run/httpd.pid" "/run/httpd/${uid}:${gid}/httpd.pid" 2>/dev/null | head -1` ###
	lsof -p $pid >&2 ###
	#/usr/sbin/apache2 -f "/var/www/user/${uid}:${gid}/conf/httpd.conf" -k graceful 2>/dev/null
	# Dilemma: When we reload, apache2cfg -c is run and may create a ssl.conf for then generated dehydrated certificates - but a reload doesn't trigger apache to load new certificate files
	# But when we restart, configuration depends on httpd.service which is already active, so apache reloads the certificates but still the old DFN ones...
	# Unfortunatly systemd has no ExecRestart :-(
	# Since everything should be on Let's Encrypt now, we don't need to reconfigure daily
	#/bin/systemctl reload "httpd@${uid}:${gid}.service" ###
	#sleep 1 ###
	/bin/systemctl restart "httpd@${uid}:${gid}.service" ###
	retval=$?; cat "/var/www/user/${uid}:${gid}/conf/httpd.conf" >&2 ###
	pid=`cat "/var/www/user/${uid}:${gid}/run/httpd.pid" "/run/httpd/${uid}:${gid}/httpd.pid" 2>/dev/null | head -1` ###
	lsof -p $pid >&2 ###
elif test -f /run/apache2/apache2.pid; then
	# Yes, logrotate.d/apache2 has already reloaded, but we hadn't rotated this VHosts logs then...	 CHECK: Is this so?!
	# FIXME: Change this to systemctl and reconsider certificate renewal like above
	#env APACHE_RUN_DIR=â¦ /usr/sbin/apache2 -k graceful 2>/dev/null	# This does not work unless we set APACHE_RUN_DIR and some others
	/bin/systemctl reload apache2.service
fi

# Within a cluster, test nodes don't have to (and should not) handle cluster-wide configuration
#test -f /etc/cluster/.test && exit 0

# Run this in the background - no one knows how long it takes to certify a stage server :-(
#setsid ssl_check "$@" &
# setsid sets a new session and process group leader, but keeps the parent process :-( so logrotate (or anacron?) kills us when the last log has been rotated
detach /usr/sbin/ssl_check "$@" 

if test -d /etc/awstats; then
	# Build statistics
	if test -z "${uid}"; then
		run_awstats "$@"
	else
		mkdir -p /var/www/log/run_awstats/"${uid}" && chown 0:9998 /var/www/log/run_awstats && chmod 755 /var/www/log/run_awstats && chown "${uid}:9998" /var/www/log/run_awstats/"${uid}" && chmod 750 /var/www/log/run_awstats/"${uid}"
#printenv >/var/www/log/apache2postrotate/$$.env
#case `hostname` in
#web*)
#case $uid in
#207437)
#		owner -u "${uid}:${gid}" -- sh -x run_awstats "$@"
#;;
#esac
#;;
#*)
		owner -u "${uid}:${gid}" -- run_awstats "$@"
#;;
#esac
	fi
fi

# Handle yesterday's error logs
for vhost in "$@"; do
	case "${vhost}" in
		stage.*|stage-*)	:;;
#		*)	docroot="`awk '$1==\"DocumentRoot\"{print$2}' \"/var/www/${vhost}/conf/vhost.conf\"`"
		*)	docroot="`awk 'BEGIN{IGNORECASE=1}$1==\"DocumentRoot\"{sub(\"^\\\"\",\"\",$2);sub(\"\\\"\$\",\"\",$2);print$2}' \"/var/www/${vhost}/conf/vhost.conf\"`"
			while echo "${docroot}" | egrep -q '\${[^}]+}'; do
				var="$(echo "${docroot}" | sed -E 's/^.*\$\{([^}]+)\}.*$/\1/')"
				# FIXME: This does not handle double-quoted values
				val="$(sed -E -n "s/^Define[[:space:]]+${var}[[:space:]]+(.*)\$/\\1/p" "/var/www/${vhost}/conf/httpd.conf")"
				docroot="$(echo "${docroot}" | sed "s!\${${var}}!${val}!g")"
			done
			if test -z "${uid}"; then
				test -f "${docroot}/.noerrormail" && continue
			else
				owner -u "${uid}:${gid}" -- test -f "${docroot}/.noerrormail" && continue
			fi
			admin="`awk '$1==\"ServerAdmin\"{print$2}' \"/var/www/${vhost}/conf/identity.conf\"`"
			analyze_error_log -a "${vhost}" -m "${admin}" -f "${docroot}/.noerrormail" "/var/www/${vhost}/log/error.log.1"
			;;
	esac
done

# Check DNS entries
# Activate when asynchronous web4 has been re-integrated
#test "$HOST" = "web1" && \
check_dns "$@"

# While DNS updates aren't realtime: Give background check_ssl some time
#sleep 42

ps faxww >&2 ###

exit 0
