#!/bin/sh
### BEGIN INIT INFO
# Provides:          fetch-rootca-cert
# Required-Start:    $local_fs $remote_fs
# Required-Stop:     $local_fs $remote_fs
# Should-Start:      $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Fetch Debian-Edu_rootCA.crt
# Description:
#   Fetch Debian Edu rootCA certificate from the main server
# X-Start-Before:    nslcd
### END INIT INFO
#
# Author: Wolfgang Schweer, <wschweer@arcor.de>
# Date:   2020-02-14

set -e

. /lib/lsb/init-functions

if [ -r /etc/debian-edu/config ] ; then
	. /etc/debian-edu/config
fi

BUNDLECRT=/etc/ssl/certs/debian-edu-bundle.crt
ROOTCACRT=/etc/ssl/certs/Debian-Edu_rootCA.crt
LOCALCACRT=/usr/local/share/ca-certificates/Debian-Edu_rootCA.crt

do_start() {

	ERROR=false

	# Remove no longer used certificate file
	rm -f $BUNDLECRT

	# RootCA cert retrieval (avoid execution on the main server, things are in place)
	if echo "$PROFILE" | egrep -q 'Main-Server' ; then
		logger -t fetch-rootca-cert "Running on the main server, exiting."
		exit 0
	fi
	if [ ! -f $LOCALCACRT ] || [ ! -s $LOCALCACRT ] ; then
		# Since Debian Edu 10, the RootCA file is distributed
		# over http (always via the host serving www.intern, by default: TJENER)
		#
		# We do an availability check for the webserver first, to provide proper
		# error reporting (see below). So, the following check merely discovers,
		# if the webserver is online at all.
		if curl -sfk --head -o /dev/null https://www.intern 2>/dev/null; then
			# Now let's see if the webserver has the "Debian Edu RootCA" file.
			# This has been the case for Debian Edu main servers (TJENER) since
			# Debian Edu 10.1.
			if curl -fk https://www.intern/Debian-Edu_rootCA.crt > $LOCALCACRT 2>/dev/null && \
				grep -q CERTIFICATE $LOCALCACRT ; then
				# Make rootCA certificate available in /etc/ssl/certs/
				ln -nsf $LOCALCACRT $ROOTCACRT
				# Integrate the rootCA certificate into /etc/ssl/certs/ca-certificates
				update-ca-certificates
				logger -t fetch-rootca-cert "Deploy the Debian Edu rootCA certificate fetched from www.intern systemwide."
			else
				# Drop $ROOTCACRT and $LOCALCACRT files, as they probably only contain some
				# 404 http error message in html.
				rm -f $LOCALCACRT
				rm -f $ROOTCACRT
				logger -t fetch-rootca-cert "Failed to fetch rootCA certificate from www.intern."
			fi
		else
			# Report an error, if www.intern is down http-wise. This can happen and is probably
			# a temporary problem that needs an admin to fix it.
			log_action_end_msg 1
			logger -t fetch-rootca-cert "Failed to connect to www.intern, maybe the web server is down."
			ERROR=true
		fi
	fi

	if $ERROR; then
		return 1
	fi
}

case "$1" in
	start)
		do_start
		;;
	stop)
		;;
	restart|force-reload)
		;;
	*)
		echo "Usage: $0 {start|stop|restart|force-reload}"
		exit 2
esac
exit 0
