#!/bin/sh

backup_cnf=/usr/local/cams/conf/backup.cnf
databases="--all-databases"
dump_options="--defaults-extra-file=$backup_cnf"
dump_options="$dump_options --create-options"
dump_options="$dump_options --single-transaction --quick"
dump_options="$dump_options --flush-privileges"
timestamp=`date +%F-%T`
dump_dir=/usr/local/cams/backup
dump_file=$dump_dir/local/$timestamp.sql
dump_errors=/tmp/dumperror$$
remote_user=root
mysqldump=/usr/local/mysql/bin/mysqldump
# mail recipient for any problem encountered
recipient=touchstone-support@mit.edu

thishost=`hostname | tr '[:upper:]' '[:lower:]'`

# Determine our peer, to which we will copy the dump file.
case "$thishost" in
idp1-cams*)
  remote_host=idp2-cams.mit.edu
  ;;
idp2-cams*)
  remote_host=idp1-cams.mit.edu
  ;;
idp3-staging*)
  remote_host=idp4-staging.mit.edu
  ;;
idp4-staging*)
  remote_host=idp3-staging.mit.edu
  ;;
*)
  echo "Warning: no peer for copying dump from $thishost" | \
    mail -s "Backup warning from $thishost" $recipient
  remote_host=
  ;;
esac

# Make sure the dump file is not world readable.
umask 077

# Dump the databases.
rm -f $dump_file $dump_errors
$mysqldump $dump_options $databases > "$dump_file" 2>$dump_errors
if [ $? -ne 0 ]; then
  mail -s "Database backup failed on $thishost" $recipient < $dump_errors
else
  # Success, compress and copy the dump file to our peer.
  gzip $dump_file
  if [ -n "$remote_host" ]; then
    scp -q $dump_file.gz $remote_user@$remote_host:$dump_dir/remote/
    if [ $? -ne 0 ]; then
      echo "Failed to copy the database dump file to $remote_host" | \
        mail -s "Dump copy to $remote_host failed" $recipient
    fi
  fi
  # Clean up dump files more than a week old.
  if [ -n "$dump_dir" ]; then
    find $dump_dir/local $dump_dir/remote -type f -mtime +7 -exec rm -f {} \;
  fi
fi

rm -f $dump_errors

exit 0
