#!/bin/bash

URL=$1
DIR=$2
CERT=$3

TMPF=`mktemp`
curl -s -m 240 -k -L $URL > $TMPF 
if [ $? -ne 0 ]; then 
   echo "Unable to download $URL: $?"
   exit 1
fi
if [ "x$CERT" != "x" ]; then
   xmlsec1 --verify --pubkey-cert-pem $CERT --id-attr:ID  urn:oasis:names:tc:SAML:2.0:metadata:EntitiesDescriptor $TMPF
   if [ $? -ne 0 ]; then 
      echo "Unable to verify $URL with $CERT: $?"
      exit 1
   fi
fi
TMPD=`mktemp -d`
xsltproc --stringparam output $TMPD xslt/import-metadata.xsl $TMPF
if [ $? -ne 0 ]; then 
   echo "Unable to import metadata from $URL: $?"
   exit 1
fi
rsync -avz $TMPD/ $DIR
rm -rf $TMPF $TMPD