#!/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 certificate 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 server CA's sertificate chain updates
DATASTEM=/usr/local/mulidata
SSLPATH=${DATASTEM}/site
DBPATHS="$SSLPATH"

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

#
# fetch latest server CA chain
#

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

#
# check for changes
#

CHANGED=0
for i in $DBPATHS
do
	diff -q $CRT ${i}/${CRT} >/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 $CRT
	cd /
	rmdir $tmpdir
	exit 0
fi
echo Server CA chain changed, updating.

#
# update CA chain
#

for i in $DBPATHS
do
	cp -f -p $CRT ${i}/${CRT}
done
rm -f $CRT
cd /
rmdir $tmpdir
echo Done.
exit 0

