require File.expand_path(File.join(File.dirname(__FILE__), '..', 'mysql'))
Puppet::Type.type(:mysql_plugin).provide(:mysql, :parent => Puppet::Provider::Mysql) do
  desc 'Manages MySQL plugins.'

  commands :mysql => 'mysql'

  def self.instances
    mysql([defaults_file, '-NBe', 'show plugins'].compact).split("\n").collect do |line|
      name, status, type, library, license = line.split(/\t/)
      new(:name    => name,
          :ensure  => :present,
          :soname  => library
         )
    end
  end

  # We iterate over each mysql_plugin entry in the catalog and compare it against
  # the contents of the property_hash generated by self.instances
  def self.prefetch(resources)
    plugins = instances
    resources.keys.each do |plugin|
      if provider = plugins.find { |pl| pl.name == plugin }
        resources[plugin].provider = provider
      end
    end
  end

  def create
    # Use plugin_name.so as soname if it's not specified. This won't work on windows as
    # there it should be plugin_name.dll
    @resource[:soname].nil? ? (soname=@resource[:name] + '.so') : (soname=@resource[:soname])
    mysql([defaults_file, '-NBe', "install plugin #{@resource[:name]} soname '#{soname}'"].compact)

    @property_hash[:ensure]  = :present
    @property_hash[:soname] = @resource[:soname]

    exists? ? (return true) : (return false)
  end

  def destroy
    mysql([defaults_file, '-NBe', "uninstall plugin #{@resource[:name]}"].compact)

    @property_hash.clear
    exists? ? (return false) : (return true)
  end

  def exists?
    @property_hash[:ensure] == :present || false
  end

  mk_resource_methods

end
