$stdout.sync = true

def host(i, h)
  return h["prefix"].to_s + "%0#{h["digit"]}d" % i
end

def host_ip_mac(mac, i, ip, h, filename)
  puts host(i + h["start_slave_num"].to_i, h) + "\t" + ip.ip_range[i] + "\t" + mac
  open(filename, "a"){|io|
    io.puts host(i + h["start_slave_num"].to_i, h) + "\t" + ip.ip_range[i] + "\t" + mac
  }
end

def get_mac(h, filename)
  cmd = "tcpdump -i #{h["eth"]} -l ip broadcast 2> /dev/null"
#  cmd = "ruby test_mac.rb #{h["eth"]}"

  ip = IP_Addr.new(h["netmask"], h["startip"], h["number"])
  mac = Array.new
  my_mac_address = [h["mac_address"].downcase, h["mac_address"].upcase]
  mac_pre = ""
  i = 0
  begin
    IO.popen(cmd){|io|
      while line = io.gets
        line = line.split[8].sub(/,$/,"")
        if (/..:..:..:..:..:../) =~ line
          mac.push(line)
          mac - my_mac_address
          mac.uniq!
          if mac_pre != mac[-1]
            if h["number"].to_i > i
              host_ip_mac(mac[-1], i, ip, h, filename)
              i = i + 1
              mac_pre = mac[-1]
              sleep 0.5
            else
              return 0
            end
            return 0 if h["number"].to_i == i
          end
        end
      end
    }
  rescue SignalException
    open(filename, "a"){|io|
      io.puts "### END OF FILE ###"
    }
    puts "Added #{mac.length} MAC Addresses."
    puts "Created \"./" + filename + "\"."
    exit 1
  end
end
