#!/usr/bin/ruby
#
# Overview
# --------
#
# This script is designed to determine the name of any remote
# backup space associated with this machine and upload the local
# archive, produced by backup2l, to this location.
#
#
# Override
# --------
#
# If there is a file "/etc/symbiosis/dns.d/backup.name" it
# is assumed to contain the name and path of a remote location to
# use for the rsync upload.
#
#
# Disabling
# ---------
#
# To disable uploads completely create the empty file named
# "/etc/symbiosis/dns.d/backup.name".
#
# Steve
# --
#

require 'symbiosis/host'

#
#  Local backup directory.
#
src = "/var/backups/"

#
# Automatically determine the primary backup space
#
name = Symbiosis::Host.primary_backup_space.to_s

#
#  If we didn't get a name then exit.
#
if name.empty?
  puts "Failed to determine backup space name.  Not uploading backup(s) to remote space."
  exit 0
end

#
#  If we got a name of the form "foo.backup.bytemark.co.uk" truncate at the
#  first part.  Otherwise use the name untouched.
#
if name =~ /\.backup\.bytemark\.co\.uk$/
  #  If the name of the machine is example.vm.bytemark.co.uk we'll expect
  # to upload to:
  #
  #    example.backup.bytemark.co.uk::example/example.vm.bytemark.co.uk/
  #
  
  fqdn = `hostname --fqdn`.chomp
  dest = name+"::"+name.split(".").first+"/"+fqdn
else
  dest = name
end

#
#  Now rsync.
#
#  If the name of the machine is example.vm.bytemark.co.uk we'll expect
# to upload to:
#
#    example.backup.bytemark.co.uk::example/example.vm.bytemark.co.uk/
#
puts "Sending backups to #{dest}...\n"

puts `rsync --bwlimit=768 --delete-before --delete-excluded --exclude 'localhost/TMP.*' --quiet --archive --recursive --perms --no-owner --no-group --human-readable #{src} #{dest}`

#
# Exit with the exit status of the rsync command
#
exit $?.exitstatus
