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


#!/usr/bin/ruby

require 'yaml'


#
#  This class either a) returns the output of running commands, or
# b) returns the output from a faked command
#
class CommandWrapper

  def CommandWrapper.run_command( str )

    if ( ENV['TEST'] && ENV['TEST_PREFIX'] )
      #
      #  Count the number of commands we've executed so far.
      #
      count = ENV['TEST_COUNT'] || '0'
      count = count.to_i
      ENV['TEST_COUNT'] = (count + 1).to_s

      #
      #  Read the output from the faked file.
      #
      #    $prefix/$count.cmd
      #
      file = "#{ENV['TEST_PREFIX']}/#{count}.cmd"
      File.open( file, "r" ).readlines().join()
    else
      `#{str}`
    end
  end
end


#
# Find the flags for each listed IPv6 address.
#
class IPv6Flags

  #
  #  Get the flags for each configured IPv6 address.
  #
  def self.flags
    c = CommandWrapper.run_command( "ip -6 addr list" )

    flags = Hash.new

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

        verbose( "IPv6 Address:#{addr} Flags:#{flag}" )
        flags[ addr ] = flag
      end
    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 the count is too high alert.
    #
    if ( 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
  end

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