control 'elastichearch tests' do
  # Required packages for Elasticsearch
  packages = %w(
    java-1.8.0-openjdk
    java-1.8.0-openjdk-devel
    unzip
    zip
  )
  packages.each do |package|
    describe package(package) do
      it { should be_installed }
    end
  end

  attribute_file = '/tmp/kitchen/node_attributes.json'
  if file(attribute_file).exist?
    node = json(attribute_file).params

    # System-wide limits, which need to be higher for ES
    nofile_soft = node['default']['elasticsearch']['ulimit']['nofile']['soft']
    nofile_hard = node['default']['elasticsearch']['ulimit']['nofile']['hard']
    describe limits_conf() do
      its('*') { should include ['soft', 'nofile', nofile_soft], ['hard', 'nofile', nofile_hard] }
    end

    # Elasticsearch cookbook checks
    describe user('elasticsearch') do
      it { should exist }
    end

    version = node['default']['elasticsearch']['elasticsearch_version']
    describe package('elasticsearch') do
      it { should be_installed }
      its('version') { should match(/#{version}/) }
    end

    # By default elasticsearch configuration file is /etc/elasticsearch/elasticsearch.yml
    # so we checks if config options exists in thhis file
    describe file('/etc/elasticsearch/elasticsearch.yml') do
      it { should exist }
      its('content') { should match(/cluster.name: #{node['default']['elasticsearch']['cluster_name']}/) }
      its('content') { should match(/node.name: #{node['default']['elasticsearch']['node_name']}/) }
      its('content') { should match(/http.port: #{node['default']['elasticsearch']['http_port']}/) }
    end

    if node['default']['elasticsearch']['elasticsearch_version'].to_s.start_with?('5')
      # Java options by default are in /etc/sysconfig/elasticsearch file
      describe file('/etc/sysconfig/elasticsearch') do
        it { should exist }
        its('content') { should match(/-XX:\+UseParNewGC/) }
        its('content') { should match(/-XX:\+UseConcMarkSweepGC/) }
        its('content') { should match(/-XX:CMSInitiatingOccupancyFraction=75/) }
        its('content') { should match(/-XX:\+UseCMSInitiatingOccupancyOnly/) }
        its('content') { should match(/-XX:\+HeapDumpOnOutOfMemoryError/) }
        its('content') { should match(/-XX:\+PrintGCDetails/) }
      end
    end

    # Logging configuration is in /etc/elasticsearch/logging.yml file
    describe file('/etc/elasticsearch/logging.yml') do
      it { should exist }
      its('content') { should match(/logger.action: #{node['default']['elasticsearch']['log_level']}/) }
    end

    describe service('elasticsearch') do
      it { should be_enabled }
    end

  else
    puts "File #{attribute_file} does not exist, skiping attribute-depending checks"
  end
end
