# frozen_string_literal: true

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_raw: 'mysql'

  def self.instances
    mysql_caller('show plugins', 'regular').split("\n").map do |line|
      name, _status, _type, library, _license = line.split(%r{\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.each_key do |plugin|
      if provider = plugins.find { |pl| pl.name == plugin } # rubocop:disable Lint/AssignmentInCondition
        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])
    self.class.mysql_caller("install plugin #{@resource[:name]} soname '#{soname}'", 'regular')

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

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

  def destroy
    self.class.mysql_caller("uninstall plugin #{@resource[:name]}", 'regular')

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

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

  mk_resource_methods
end
