
Puppet::Type.newtype(:vmware_config) do
    @doc = "Modify /etc/vmware/locations file."

    @@locations = "/etc/vmware/locations"
    @@netmap = "/etc/vmware/netmap.conf"

    def bucket
	filebucket = catalog.resource(:filebucket, "puppet")
	(filebucket || Puppet::Type.type(:filebucket).mkdefaultbucket).bucket
    end

    def netmap
	config = parse()
	data = "# This file is automatically generated.\n"
	data += "# Hand-editing this file is not recommended.\n"
	data += "\n"
	id = 0
	(0..254).each do |n|
	    if name = config["VNET_#{n}_NAME"]
		data += "network#{id}.name = \"#{name}\"\n"
		data += "network#{id}.device = \"vmnet#{n}\"\n"
		id += 1
	    end
	end
	current = File.open(@@netmap).read
	if data != current
	    bucket.backup(@@netmap)
	    File.open(@@netmap, "w").print data
	end
    end

    def parse
	config = {}
	File.open(@@locations).each { |line|
	    if m = /^answer ([A-Z0-9_]+) (.+)$/.match(line)
		config[m[1]] = m[2]
	    elsif m = /^remove_answer ([A-Z0-9_]+)$/.match(line)
		config.delete(m[1])
	    end
	}
	return config
    end

    newparam(:name) do
	desc "Configuration key name"
	newvalues(/^[A-Z0-9_]+$/)
    end

    newproperty(:ensure) do
	def retrieve
	    config = @resource.parse()
	    if config.has_key?(@resource.name)
		config[@resource.name]
	    else
		:absent
	    end
	end

	newvalue(:absent) do
	    @resource.bucket.backup(@@locations) if File.exists?(@@locations)
            open(@@locations, File::WRONLY|File::APPEND) do |f|
		f.print "remove_answer %s\n" % @resource.name
	    end
	    if @resource.name =~ /^VNET_/
		@resource.netmap()
	    end
	end

	newvalue(/.+/) do
	    @resource.bucket.backup(@@locations) if File.exists?(@@locations)
	    open(@@locations, File::WRONLY|File::APPEND) do |f|
		f.print "remove_answer %s\n" % @resource.name
		f.print "answer %s %s\n" % [@resource.name, value]
	    end
	    if @resource.name =~ /^VNET_/
		@resource.netmap()
	    end
	end
    end

end
