#!/usr/bin/ruby
#
# Ensure that any IPv6 addresses are not marked as "dadfailed".
#

require 'yaml'

#
# Allow access to our common-code.
#
$LOAD_PATH << '/usr/share/bytemark'
$LOAD_PATH << '../lib/bytemark' if ENV['TEST'] && ENV['TEST_PREFIX']

require 'healthcheck/command_output'


#
# Find the flags for each listed IPv6 address.
#
class IPv6Flags
  #
  #  Get the flags for each configured IPv6 address.
  #
  def self.flags
    c = Bytemark::Healthcheck::CommandWrapper.run_command('ip -6 addr list')

    flags = {}

    c.split("\n").each do |line|
      next unless line =~ /\s+inet6 ([^ ]+)\s+(.*)$/
      addr = Regexp.last_match(1).dup
      flag = Regexp.last_match(2).dup

      verbose("IPv6 Address:#{addr} Flags:#{flag}")
      flags[addr] = flag
    end

    flags
  end
end

if __FILE__ == $PROGRAM_NAME

  def verbose(str)
    STDERR.puts(str)
  end

  to_raise = []

  #
  #  Count pending messages.
  #
  addrs = IPv6Flags.flags
  verbose("Found #{addrs.keys.count} addreses")

  addrs.each do |key, val|
    #
    #  If we see a `failed` status against an address we're in trouble.
    #
    next unless val =~ /failed/i
    h = {}
    h[:id] = "ipv6-#{key}"
    h[:summary] = "IPv6 Address #{key} has bad flags"
    h[:detail] = "<p>There flags for the IPv6 address #{key} are bogus - #{val}.  We should not see 'failed' in those flags.</p>"
    to_raise.push(h)
  end

  #
  #  Show the output.
  #
  puts YAML.dump(to_raise)
  exit(0)
end
