require 'rubygems'
require 'sinatra'
DATAFILE = "hostdata.yml"
def get_data
if File.readable?(DATAFILE)
@hosts, @errors = YAML.load_file(DATAFILE)
else
@hosts = {}
@errors = []
end
end
def save_data
File.open(DATAFILE,"w") do |out|
YAML.dump([@hosts,@errors], out)
end
end
get '/' do
get_data
erb <<-END
Hosts so far:
<% @hosts.keys.sort.each do |mac|
host = @hosts[mac] %>
- <%=mac%> -> name=<%=host[:name]%> ip=<%=host[:ip]%> updated at <%=host[:time]%>
<% end %>
Errors logged:
<% @errors.each do |line| %>
- <%=line%>
<% end %>
END
end
get '/hosts' do
headers 'Content-Type' => 'text/plain'
get_data
resp = "\# Host file data created by fakedns.rb\n"
@hosts.keys.sort.each do |mac|
host = @hosts[mac]
resp += "#{host[:ip]} #{host[:name]}\n"
end
resp
end
post '/' do
get_data
mac = params[:mac].strip
name = params[:name].strip
ip = params[:ip].strip
@new_errors = []
if mac.size == 0 || name.size == 0 || ip.size == 0
errormsg = "#{Time.now}: Error adding host '#{name}' with ip '#{ip}' from mac address '#{mac}' - all parameters must be supplied"
@new_errors << errormsg
@errors << errormsg
end
@hosts.each do |other_mac, other_host|
if other_host[:name] == name && other_mac != mac
errormsg = "#{Time.now}: Error adding host '#{name}' with ip '#{ip}' from mac address '#{mac}' - collides with host '#{other_host[:name]}' with ip '#{other_host[:ip]}' from mac address '#{other_mac}'"
@new_errors << errormsg
@errors << errormsg
end
end
if @new_errors.size == 0
@hosts[mac] = {:name => name, :ip => ip, :time => Time.now.to_s}
end
save_data
if @new_errors.size > 0
status 500
erb <<-END
Errors occurred:
<% @new_errors.each do |error| %>
- <%=error%>
<% end %>
END
else
'ok - go to main page for results, or /hosts for hosts file snippet.'
end
end