#!/bin/sh

# Download and install the latest MIT metadata.  This should be
# run regularly from cron.  It sends mail upon failure.

# Adjust the following line as needed for your installation!
shibboleth_etc_dir=/usr/local/shibboleth-idp/etc

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

host=`hostname`

touchstone_metadata_dir=http://web.mit.edu/touchstone/shibboleth/config/metadata
mit_metadata=MIT-metadata.xml
mit_metadata_url="${touchstone_metadata_dir}/${mit_metadata}"

cd $shibboleth_etc_dir || {
  echo "Cannot cd to $shibboleth_etc_dir" | \
    mail -s "metadata update failed on $host" $recipient
  exit 1
}
umask 022

case `uname` in
SunOS)
  PATH=$PATH:/usr/sfw/bin
  export PATH
  ;;
esac

# Download the current MIT metadata file.
rm -f "${mit_metadata}.new"
wget --output-document="${mit_metadata}.new" "$mit_metadata_url" \
  > /dev/null 2>&1 || {
  mail -s "Download of $mit_metadata_url failed on $host" $recipient
  exit 1
}

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