#!/bin/bash

set -e

DEFAULT="/etc/default/authentic2"
BASEDIR=`dirname $0`
METADATA_TMP=`tempfile`
FILTERS_TMP=`tempfile`
CERTIFICATE_TMP=`tempfile`

function cleanup {
	rm -f $METADATA_TMP $FILTERS_TMP $CERTIFICATE_TMP;
}

trap "cleanup" EXIT

if [ -f  ]; then
	. /etc/default/authentic2
else
	. $BASEDIR/`basename $DEFAULT`
fi

if ! wget --quiet $RENATER_METADATA -O$METADATA_TMP; then
	echo ERROR: unable to retrieve metadata from $RENATER_METADATA
	exit 1
fi

if ! wget --quiet $RENATER_ATTRIBUTE_FILTERS -O$FILTERS_TMP; then
	echo ERROR: unable to retrieve attribute filters from $RENATER_ATTRIBUTE_FILTERS
	exit 1
fi

if ! wget --quiet $RENATER_CERTIFICATE -O$CERTIFICATE_TMP; then
	echo ERROR: unable to retrieve Renater metadata signing certificate from $RENATER_CERTIFICATE
	exit 1
fi

if ! xmllint $METADATA_TMP >/dev/null; then
	echo ERROR: xmllint failed on renater metadata
	exit 1
fi

if ! xmllint $FILTERS_TMP >/dev/null; then
	echo ERROR: xmllint failed on renater attribute filters
	exit 1
fi

# Verify metadata signature
if ! xmlsec1 --verify --id-attr:ID EntitiesDescriptor --pubkey-cert-pem $CERTIFICATE_TMP --enabled-key-data key-name $METADATA_TMP 2>/dev/null >/dev/null; then
	echo ERROR: unable to validate signature on $RENATER_METADATA
	exit 1
fi

# Load metadataas
authentic2-ctl sync-metadata --source=renater --shibboleth-attribute-filter-policy=$FILTERS_TMP --sp -v1 $METADATA_TMP
