dn42-scripts/scripts/dhcp
2015-01-13 08:19:32 +01:00

89 lines
2.4 KiB
Ruby
Executable File

#!/usr/bin/ruby
require_relative "utils"
require "optparse"
class DhcpRegistry < Registry
def add_lease(name, macaddress, ipv4, ipv6)
data["network"][name] ||= {}
host = data["network"][name]
host["macaddress"] = macaddress
host["ipv4"] = ipv4 if ipv4
host["ipv6"] = ipv6 if ipv6
end
def remove_lease(name)
if data["network"].delete(name).nil?
die "no such lease name #{name} in registry.json"
end
end
def update_leases
template_path = Pathname.new(File.expand_path("../../templates", __FILE__))
dhcp_template = Template.new(template_path.join("dhcp.conf.erb"))
static_leases = data["network"].select do |name, data|
data["mac"] && (data["ipv4"] || data["ipv6"])
end.map do |name, data|
TemplateContext.new(data.merge(name: name))
end
dhcp_path = Pathname.new(File.expand_path("../../dhcp.peers.conf", __FILE__))
File.open(dhcp_path, "w+").write(dhcp_template.render(leases: static_leases))
end
end
GLOBAL_OPTIONS = OptionParser.new do |opts|
opts.banner = "Usage: dhcp [options] [subcommand [options]]"
opts.separator ""
opts.separator <<HELP
Available subcommands:
add [options] NAME MACADDRESS: add dhcp lease
remove [options] NAME: remove dhcp static lease
See 'dhcp COMMAND --help' for more information on a specific command.
HELP
end
def add_command(registry, args)
ipv4, ipv6 = nil, nil
parser = OptionParser.new do |opts|
opts.banner = "Usage: dhcp add [options] NAME MACADDRESS"
opts.on("-4", "--ipv4 ADDRESS", "set fixed ipv4 address") do |address|
ipv4 = address
end
opts.on("-6", "--ipv6 ADDRESS", "set fixed ipv6 address") do |address|
ipv6 = address
end
end.order!
if ARGV.size < 2
$stderr.puts "no enough arguments"
die(parser.help)
end
name, macaddress = args
registry.add_lease(name, macaddress, ipv4, ipv6)
end
def remove_command(registry, args)
parser = OptionParser.new do |opts|
opts.banner = "Usage: dhcp remove NAME"
end.order!
if args.empty?
$stderr.puts "no enough arguments"
die(parser.help)
end
registry.remove_lease(args.first)
end
GLOBAL_OPTIONS.order!
registry = DhcpRegistry.new
case command = ARGV.shift
when "add"
add_command(registry, ARGV)
when "remove"
remove_command(registry, ARGV)
when nil # just update
else
die "unknown subcommand #{command}"
end
registry.save
registry.update_leases