require 'rubygems'
require 'activeresource'
API_PASSWORD = 'API_KEY_HERE'
API_ADDRESS = "https://#{API_PASSWORD}@api.slicehost.com/"
NAMESERVERS = ["ns1.slicehost.com", "ns2.slicehost.com", "ns3.slicehost.com"]
VERBOSE = true
DEBUG = false
class Zone < ActiveResource::Base
self.site = API_ADDRESS
end
class Record < ActiveResource::Base
self.site = API_ADDRESS
end
class ZoneParser
attr_accessor :records
attr_accessor :domain
def initialize(filename, domain)
@records = Array.new
@domain = domain
File.open(filename, 'r').each_line do |line|
next if (line =~ /SOA/)
next if (line =~ /^\s*\;/)
parts = line.split(/\s\s*/)
next if (parts.size == 0)
next if ( (parts.first == "" or parts.first == "@") && !parts[1].match(/^\D\D*$/) )
next if (parts[1] == "NS")
p line if (DEBUG)
if(parts.first == "" or parts.first == "@" )
parts[0] = domain + "."
end
if(parts[1] == "IN")
parts = [parts[0], parts[2], parts[3], parts[4..parts.size].join(" ")]
end
ap = {
:record_type => parts[1],
:name => parts[0],
:data => parts.last,
:ttl => 8000,
:active => 'Y',
:aux => 0
}
if(parts.size == 4)
ap[:aux] = parts[2]
end
p ap if(DEBUG)
@records << ap
end
end
def sync(clear = true)
z = Zone.find(:first, :params => {'origin' => @domain + "."})
p z if(DEBUG)
if( not z):
z = Zone.new({
:origin => @domain,
:ttl => 8000,
:active => 'Y'
})
z.save unless z.nil?
end
if(not z)
raise Exception.new("Error finding/creating zone for #{@domain}")
elsif(VERBOSE)
print "Syncing Zone: #{@domain}\n"
end
p z if(DEBUG)
if(clear)
print "\nRemoving all records for zone: #{@domain}\n" if(VERBOSE)
Record.find(:all, :params => {:zone_id => z.id}).each do |r|
r.destroy unless r.nil?
p r if (DEBUG)
print "\t- #{r.name} #{r.record_type} #{r.data}\n" if(VERBOSE)
end
end
print "\nAdding records to zone: #{@domain}\n" if(VERBOSE)
base = {
:record_type => "NS",
:name => @domain + ".",
:ttl => 8000,
:active => 'Y',
:aux => 0
}
NAMESERVERS.each do |ns|
base[:data] = ns
@records << base.dup
end
@records.each do |r|
r[:zone_id] = z.id
rec = Record.new(r)
rec.save unless rec.nil?
if(not rec or rec.errors.size > 0)
print "\t* ERROR ADDING #{r[:name]} #{r[:record_type]} #{r[:data]}\n"
p rec
elsif(rec && VERBOSE)
p rec if(DEBUG)
print "\t+ #{r[:name]} #{r[:record_type]} #{r[:data]}\n"
end
end
end
end
z = ZoneParser.new("test_zone.txt", "hab.la")
z.sync