#!/bin/sh

# Refresh the InCommon metadata, by downloading the current version
# and verifying its signature.

JAVA_HOME=/usr/java/jdk
IDP_HOME=/usr/local/shibboleth-idp
export JAVA_HOME IDP_HOME

# Set the email address to receive error messages.
recipient=touchstone-support@mit.edu

host=`hostname`

keystore=$IDP_HOME/etc/incommon.jks
alias=sitesigner
password=incommon
uri=http://wayf.incommonfederation.org/InCommon/InCommon-metadata.xml
file=$IDP_HOME/etc/InCommon-metadata.xml

umask 022

# Download and verify the current file.
rm -f "${file}.new"
$IDP_HOME/bin/metadatatool -i "$uri" -k "$keystore" -a "$alias" \
  -p "$password" -o "${file}.new" || {
  mail -s "refresh of InCommon metadata failed on $host" $recipient
  exit 1
}

# Install the downloaded file if different from what we have.
if [ -s "${file}.new" ]; then
  if cmp -s "${file}.new" "${file}" ; then
    rm -f "${file}.new"
  else
    if [ -f "${file}" ]; then
      cp -p "${file}" "${file}.old"
    fi
    mv "${file}.new" "${file}" && chmod 644 "${file}"
  fi
else
  mail -s "Failed to download $uri on $host" $recipient
  exit 1
fi
