require 'puppet/provider/package'

# Puppet provider for iMil's pkgin (binary pkgsrc). Based on openbsd provider
# This is not bug free, feel free to improve
#
# Nicolas Szalay <nico@gcu.info>
#
Puppet::Type.type(:package).provide :pkgin, :parent => Puppet::Provider::Package do
    include Puppet::Util::Execution
    desc "pkgin provider"

	# add typical pkgsrc dirs to the PATH
	ENV["PATH"] = ENV["PATH"]+":/opt/pkg/bin:/usr/pkg/bin/opt/pkg/sbin:/usr/pkg/sbin"

	commands :pkgin => "pkgin"

	def self.instances
		packages = []
		regex = %r{(\S+)(-)(.*?)(\s+)(.*)}
		# we rely on pkg_info to know which packages are installed
		cmd="pkg_info -a"

		begin
			Puppet.debug "Running '%s'" % cmd
			execpipe(cmd) { |pkglist|
				hash={}
				pkglist.each { |line|
					if (match=regex.match(line)) then
						hash[:name]=match[1]
						hash[:version]=match[3]
						hash[:description]=match[5]

						packages << new(hash)
						hash={}
					end
				}
			}
		rescue Puppet::ExecutionFailure
			return nil
		end

		return packages
	end

    def install
		should = @resource[:ensure]
		pkgin ["-y", "in", @resource[:name] ]
    end

	def uninstall 
		pkgin ["-y", "rm", @resource[:name] ]
	end

    def query
        hash = {}
		hash[:ensure] = :absent
		regex=%r{(\S+)(-)(.*?)(\s+)(.*)}

		begin
			cmd = "pkgin ls"
			execpipe(cmd) { |process|
				process.each { |line|
					if match = regex.match(line)
						if match[1] == @resource[:name]
							Puppet.debug " %s is present" % @resource[:name]
							hash[:ensure] = :present
						end
					end
				}
			}
		end

		return hash
    end

end

