#!/usr/bin/ruby
#
# Overview
# --------
#
# This script is designed to determine the name of any remote
# backup space associated with this machine and download any files
# stored within that backup space, previously produced by backup2l,
# to the local machine.
#
# This is designed to ensure that no local backups are lost if the
# machine is re-imaged, or local backups are removed due to user-error
#
#
# 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/downloads completely create the empty file named
# "/etc/symbiosis/dns.d/backup.name".
#
# Steve
# --
#

require 'symbiosis/host'
require 'fileutils'

#
#  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?
  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$/
  # Grab the FQDN
  fqdn = `hostname --fqdn`.chomp
  dest = name+"::"+name.split(".").first+"/"+fqdn
else
  dest = name
end

FileUtils.mkdir_p("#{src}/localhost") unless File.directory?("#{src}/localhost")

#
#  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 "Ensuring directory structure is present..."
puts `rsync --quiet --perms --human-readable --dirs #{src}/localhost #{dest}/`

puts "\nSynchronising backups from #{dest}/localhost..."
puts `rsync --quiet --archive --recursive --no-perms --no-owner --no-group --human-readable #{dest}/localhost/ #{src}/localhost/`

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