#!/bin/sh

# Download and install the latest SP metadata.  This should be run
# regularly from cron on the WAYF/DS servers.  It sends mail upon
# failure.

# We install the metadata in the SWITCHwayf directory.
switchwayf_dir=/var/www/SWITCHwayf

# 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
sp_metadata=MIT-all-SP-metadata.xml
sp_metadata_url="${touchstone_metadata_dir}/${sp_metadata}"

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

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

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