#!/bin/sh
# Copyright (c) 2019 Jack Burton <jack@saosce.com.au>
# Copyright (c) 2021 Muli Management, 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 host CA's CRL chain
# for use by cdb & login_db postgres 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
PGSTEM=/usr/local/mulipg
CDBPATH=${PGSTEM}/cdb${CONTRACT}pgsql/data
LOGINDBPATH=${PGSTEM}/login_dbpgsql/data
SSLPATH=${PGSTEM}/ssl
#DBPATHS="$CDBPATH $LOGINDBPATH"
DBPATHS="$SSLPATH"

# where to get the CRL chain from
CRL=host-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 host 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 Host 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. Reloading postgres.

#
# Reload configuration for MULI postgres instances
#

systemctl reload postgresql
if test $? -ne 0
then
	echo FAILED >&2
	exit 1
fi
echo Done.
) > /dev/null
exit 0

