require "ostruct" require "fileutils" require "erb" require "json" require "pathname" require "pry" require "netaddr" class Registry PATH = Pathname.new(File.expand_path("../../jails.json", __FILE__)) def initialize @data = JSON.load(File.open(Registry::PATH)) end attr_accessor :data def save f = File.open(Registry::PATH, "w+") f.puts JSON.pretty_generate(@data) f.close end end def atomic_write(path, content) dir = File.dirname(path) unless Dir.exist?(dir) FileUtils.mkdir_p(dir) end temp_path = path.to_s + ".tmp" File.open(temp_path, 'w+') do |f| f.write(content) end FileUtils.mv(temp_path, path) end def sh(cmd, *args) puts "$ #{cmd} "+ args.map {|a| "'#{a}'" }.join(" ") system(cmd, *args) end def die(msg) $stderr.puts(msg) exit(1) end def next_free_subnet(subnet, assigned_subnets) subnet.enumerate(Limit: 1E4, Short: true)[1..1E4].each do |cidr| assigned = assigned_subnets.find { |s| s.contains?(cidr) || s == cidr } return cidr unless assigned end end class TemplateContext < OpenStruct def get_binding binding end end class Template def initialize(path) @erb = ERB.new(File.read(path), nil, '-') end def render(params={}) @erb.result(TemplateContext.new(params).get_binding) end end