#!/bin/sh
#
# Fetches Debian Edu rootCA certificate from the main server
#
# Author: Wolfgang Schweer, <wschweer@arcor.de>
# Date:   2020-02-14
#

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

# Don't use the proxy for accesing www.intern
if [ -n "${no_proxy}" ]; then
        no_proxy="${no_proxy},"
fi
export no_proxy="${no_proxy}www.intern"

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

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

# RootCA cert retrieval (avoid execution on the main server, things are in place)
case $PROFILE in
*Main-Server*)
    logger -t fetch-rootca-cert "Running on the main server, exiting."
    exit 0
    ;;
esac

if [ -f $LOCALCACRT ] && [ -s $LOCALCACRT ] ; then
    # The cert file already exists, nothing to do.
    exit 0
fi

if [ -z "$(dig +short A www.intern)" ] ; then
    # If the main server is not resolvable, we are not part of a DebianEdu
    # network, no need to report an error.
    exit 0
fi

# 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.
    logger -t fetch-rootca-cert "Failed to connect to www.intern, maybe the web server is down."
    exit 1
fi
