#!/usr/bin/env ruby

require 'rubygems'
require 'rubydns'
require 'ipaddr'

$VERBOSE = true

DNS1 = '62.236.255.181'
DNS2 = '62.236.255.182'
DOMAIN = 'ip.fi'

def main
  socket_ntp1 = UDPSocket.new
  #socket_ntp2 = UDPSocket.new
  socket_ntp1.bind(DNS1, 53)
  #socket_ntp2.bind(DNS2, 53)

  RubyDNS::run_server(:listen => [socket_ntp1]) do
    match(/\.ip\.fi$/, :AAAA) do |m,t|
      name = t.question.to_s
      answer = IPAddr.new(name.split(/\.ip\.fi.*/).first.to_i(36), family=Socket::AF_INET6).to_s
      t.respond!(answer)
    end

    match(//, :PTR) do |m,t|
      addr = t.question.to_s
      addr =  addr.split('.ip6.arpa').first.delete('.').reverse.scan(/..../).join(':')
      answer = [IPAddr.new(addr).to_i.to_s(36), DOMAIN].join('.')
      t.respond!(Resolv::DNS::Name.create(answer))
    end
  end
end