#!/usr/bin/env bash
#
# Script to backup (rsync) the Trac projects on another machine
#
# Written by Michel Jouvin - CNRS/LAL - 15/7/2019

backup_host=tracsrv2.lal.in2p3.fr
backup_remote_user=root
backup_directory=/wwwmirror/trac-backup
trac_projects=/pdisk/trac/projects
trac_production_hostname=trac.lal.in2p3.fr
backup_ssh_key=/pdisk/trac/site-config/ssh/trac_backup_rsa
backup_ssh_known_hosts=/pdisk/trac/site-config/ssh/trac_known_hosts
admin_email=exploitation-staff@lal.in2p3.fr
rsync_ssh_cmd="ssh -i ${backup_ssh_key} -o UserKnownHostsFile=${backup_ssh_known_hosts}"

write_msg() {
    echo "$(date --iso-8601=seconds) - $*"
}

if [ "$(hostname)" != ${trac_production_hostname} ]
then
    write_msg "ERROR: this instance hostname ($(hostname)) is not the production one (${trac_production_hostname}, backup not done"
    exit 1
fi

write_msg "Syncing Trac projects (${trac_projects}) to ${backup_directory} on ${backup_host}"
backup_dest=${backup_remote_user}@${backup_host}:${backup_directory}
rsync_output=$(rsync -a --rsh "${rsync_ssh_cmd}" ${trac_projects}/* ${backup_dest} 2>&1)
status=$?
if [ -n "${rsync_output}" ]
then
    echo "${rsync_output}"
fi
if [ ${status} -eq 0 ]
then
    write_msg "Syncing of Trac projects completed"
else
    write_msg "Some errors occured when syncing Trac projects"
    mailx -s "Trac backup failure" ${admin_email} <<EOF
An error occured when syncing Trac projects to ${backup_dest}.
Please check log file.

rsync command output was:
-----
${rsync_output}
----
EOF
fi
