require 'chef/mixin/command'

class Chef
  class Recipe

    include Chef::Mixin::Command

    def install_egg(name, options={})
      version     = options.delete(:version)
      module_name = options.delete(:module) || name
      file_name = options.delete(:file) || name
      if not is_installed?(file_name)
        Chef::Log.debug("Egg Not installed: #{name}")
        install(name, version)
      else
        if version
          #check version, crappy strict equality
          current_version = get_version(module_name)
          Chef::Log.debug("#{version} -> #{current_version}")
          if current_version != version.to_s
            Chef::Log.debug("Egg update: #{name} #{current_version} -> #{version}")
            install(name, version)
          end
        end
      end
    end

    private

    def install(name, version)
      name = "#{name}==#{version}" if version
      Chef::Log.info("Installing #{name} at version #{version}")
      bash "install_egg_#{name}" do
        code <<-EOF
            easy_install-2.6 #{name}
        EOF
      end
    end

    def is_installed?(name)
      command = "python26 -c \"import sys; print sys.path\""
      check   = false
      popen4(command) do |pid, stdin, stdout, stderr|
        stdout.each do |line|
          if line.include? "#{name}"
            check = true
          end
        end
      end
      check
    end

    def get_version(module_name)
      package_version = nil
      command         = "python26 -c \"import #{module_name}; print #{module_name}.__file__\""
      status          = popen4(command) do |pid, stdin, stdout, stderr|
        install_location = stdout.readline
        install_location[/\S\S(.*)\/(.*)-(.*)-py(.*).egg\S/]
        package_version = $3
      end
      package_version
    end

  end
end