#!/bin/sh
# Copyright (c) 2020 Muli Management Pty Ltd, Wahroonga, NSW, Australia
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
# 
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

# simple script to update server CA's CRL chain
# for use by mbbag instances on MULI V15 contract containers

# get contract number for this container
# (hostname is of the form cXXXXX)
CONTRACT=`hostname | tr -d c`

# define databases which need CRL updates
DATASTEM=/usr/local/mulidata
SSLPATH=${DATASTEM}/site
DBPATHS="$SSLPATH"

# where to get the CRL chain from
CRL=server-chain.crl.pem
URL=http://ca.muli.com.au/${CRL}
WGET_FLAGS="--retry-connrefused --waitretry=10 --read-timeout=20 --timeout=15 -t 100"

(

#
# fetch latest CRL chain
#

tmpdir=`mktemp -d`
cd $tmpdir
wget $WGET_FLAGS $URL >/dev/null 2>&1
if test $? -ne 0
then
	echo "failed to fetch server CRL chain" >&2
	rm -f $CRL
	cd /
	rmdir $tmpdir
	exit 1
fi
chmod 0644 $CRL
chown root:root $CRL

#
# check for changes
#

CHANGED=0
for i in $DBPATHS
do
	diff -q $CRL ${i}/${CRL} >/dev/null 2>&1
	if test $? -ne 0
	then
		CHANGED=1
	fi
done
if test $CHANGED -eq 0
then
	# no changes, nothing to do
	rm -f $CRL
	cd /
	rmdir $tmpdir
	exit 0
fi
echo Server CRL chain changed, updating.

#
# update CRL chains
#

for i in $DBPATHS
do
	cp -f -p $CRL ${i}/${CRL}
done
rm -f $CRL
cd /
rmdir $tmpdir
echo Done.
) > /dev/null
exit 0

