class Gitlab::QA::Component::LDAP

def add_network_alias(name)

def add_network_alias(name)
  @network_aliases.push(name)
end

def enable_tls(status)

def enable_tls(status)
  @environment['LDAP_TLS'] = 'false' unless status
end

def hostname

def hostname
  "#{name}.#{network}"
end

def initialize

def initialize
  @docker = Docker::Engine.new
  @environment = {}
  @volumes = {}
  @network_aliases = []
  @volumes[FIXTURE_PATH] = BOOTSTRAP_LDIF
end

def instance

def instance
  raise 'Please provide a block!' unless block_given?
  prepare
  start
  yield self
ensure
  teardown
end

def name

def name
  @name ||= "openldap-#{SecureRandom.hex(4)}"
end

def password

def password
  LDAP_PASSWORD
end

def prepare

def prepare
  @docker.pull(LDAP_IMAGE, LDAP_IMAGE_TAG)
  return if @docker.network_exists?(network)
  @docker.network_create(network)
end

def pull

def pull
  @docker.pull(LDAP_IMAGE, LDAP_IMAGE_TAG)
end

def restart

def restart
  @docker.restart(name)
end

def set_gitlab_credentials

def set_gitlab_credentials
  ::Gitlab::QA::Runtime::Env.ldap_username = username
  ::Gitlab::QA::Runtime::Env.ldap_password = password
end

def start

def start
  # copy-service needed for bootstraping LDAP user:
  # https://github.com/osixia/docker-openldap#seed-ldap-database-with-ldif
  docker.run(LDAP_IMAGE, LDAP_IMAGE_TAG, '--copy-service') do |command|
    command << '-d '
    command << "--name #{name}"
    command << "--net #{network}"
    command << "--hostname #{hostname}"
    @volumes.to_h.each do |to, from|
      command.volume(to, from, 'Z')
    end
    @environment.to_h.each do |key, value|
      command.env(key, value)
    end
    @network_aliases.to_a.each do |network_alias|
      command << "--network-alias #{network_alias}"
    end
  end
end

def teardown

def teardown
  raise 'Invalid instance name!' unless name
  @docker.stop(name)
  @docker.remove(name)
end

def to_config

def to_config
  config = YAML.safe_load <<~CFG
    main:
      label: LDAP
      host: #{hostname}
      port: #{LDAP_PORT}
      uid: 'uid'
      bind_dn: #{BIND_DN}
      password: #{ADMIN_PASSWORD}
      method: 'plain'
      base: #{BASE_DN}
      user_filter: ''
      group_base: #{GROUP_BASE}
      admin_group: #{ADMIN_GROUP}
      external_groups: ''
      sync_ssh_keys: false
  CFG
  # Quotes get eaten up when the string is set in the environment
  config.to_s.gsub("\"", "\\\"")
end

def username

def username
  LDAP_USER
end