#!/usr/bin/ruby
# 
# NAME
#   which-backup-space - determine which backup space is to be used.
#
# SYNOPSIS
#   which-backup-space [ --help ] [ --verbose ] [ --show-all ] [ --manual ]
#
# OPTIONS
#   --help        Show the help information for this script.
#   --verbose     Show debugging information.
#   --show-all    Show all backup spaces for all IPs on the machine
#   --manual      Display the manpage
#
# This script just checks which backup space is allocated to an individual IP.
#
# AUTHOR
#
#   Patrick J. Cherry <patrick@bytemark.co.uk>
#

#
#  Modules we require
#

require 'getoptlong'

opts = GetoptLong.new(
    [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
    [ '--manual', '-m', GetoptLong::NO_ARGUMENT ],
    [ '--verbose', '-v', GetoptLong::NO_ARGUMENT ],
    [ '--show-all', '-a', GetoptLong::NO_ARGUMENT ]
)

manual = help = false
$VERBOSE = false
show_all = false

opts.each do |opt,arg|
  case opt
    when '--help'
      help = true
    when '--manual'
      manual = true
    when '--verbose'
      $VERBOSE = true
    when '--show-all'
      show_all = true
  end
end

#
# Output help as required.
#
if help or manual
  require 'symbiosis/utils'
  Symbiosis::Utils.show_help(__FILE__) if help
  Symbiosis::Utils.show_manual(__FILE__) if manual
  exit 0
end

#
# Don't need range until here to allow generation of manpages.
#
require 'symbiosis/range'

if ARGV.length > 0

  # Collect each of the args, rejecting duff IPs.

  ips = ARGV.collect do |arg| 
    begin
      Symbiosis::IPAddr.new(arg)
    rescue ArgumentError
      warn "Could not parse '#{arg}' as an IP address"
      # do nothing
      nil
    end
  end.reject{|ip| ip.nil? }
else
  ips = Symbiosis::Range.ip_addresses
end

backup_spaces = Symbiosis::Range.backup_spaces(ips)

exit 1 if backup_spaces.empty?

if show_all
  puts backup_spaces.join("\n")
else
  puts backup_spaces.first
end

