#!/usr/bin/ruby
# 
# NAME
#   symbiosis-ip - Determine the primary IP address of this system
#
# SYNOPSIS
#   symbiosis-ip [ --all ] [ --ipv4 ] [ --ipv6 ] [ --verbose ] [ --help ]
#
# OPTIONS
#   --all         Show all available addresses on the system, not just the
#                 primary one.
#
#  --ipv4         Show IPv4 addresses
#
#  --ipv6         Show IPv6 addresses
#
#   --help        Show the help information for this script.
#
#   --verbose     Show debugging information.
#
# Output the system's primary IP address. This is determined as being the
# address with the smallest CIDR prefix on the interface which has the default
# route. IPv4 addresses are given in preference to IPv6, unless the options
# specify otherwise.
#
# 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 ],
    [ '--all', '-a', GetoptLong::NO_ARGUMENT ],
    [ '--ipv4', '-4', GetoptLong::NO_ARGUMENT ],
    [ '--ipv6', '-6', GetoptLong::NO_ARGUMENT ]
)

manual = help = false
$VERBOSE = false
show_all = false
ipv6 = false
ipv4 = false

opts.each do |opt,arg|
  case opt
    when '--help'
      help = true
    when '--manual'
      manual = true
    when '--verbose'
      $VERBOSE = true
    when '--all'
      show_all = true
    when '--ipv6'
      ipv6 = true
    when '--ipv4'
      ipv4 = 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, allowing us to generate the manpage.
#
require 'symbiosis/host'

addresses = []

if show_all
  addresses << Symbiosis::Host.ipv6_addresses if ipv6
  addresses << Symbiosis::Host.ipv4_addresses if ipv4
  addresses << Symbiosis::Host.ip_addresses if addresses.empty?
else
  addresses << Symbiosis::Host.primary_ipv6 if ipv6
  addresses << Symbiosis::Host.primary_ipv4 if ipv4
  addresses << Symbiosis::Host.primary_ip if addresses.empty?
end

puts addresses.join(" ")

