databag_name = node['datadog']['tomcat']['jmx_databag']
databag_item_name = node['datadog']['tomcat']['jmx_databag_item']

if databag_name && databag_item_name
  begin
    data_bag_item_content = data_bag_item(databag_name, databag_item_name)
    Chef::Log.info("Found databag #{databag_name}/#{databag_item_name}; parsing now")
    node.default['datadog']['tomcat']['jmx_username'] = data_bag_item_content['username']
    node.default['datadog']['tomcat']['jmx_password'] = data_bag_item_content['password']

    node['datadog']['tomcat']['instances'].each do |instance_name, _instance|
      node.default['datadog']['tomcat']['instances'][instance_name]['jmx_username'] = data_bag_item_content['username']
      node.default['datadog']['tomcat']['instances'][instance_name]['jmx_password'] = data_bag_item_content['password']
    end
  rescue
    Chef::Log.error("Cannot find databag #{databag_name}/#{databag_item_name}")
  end
else
  Chef::Log.error("Databag items not set: '#{databag_name}' and '#{databag_item_name}'")
end

datadog_templates = node['datadog']['templates']
if node['datadog']['enabled']
  node.default['logrotate']['global']['/var/log/datadog/*.log'] = {
    'create' => '0600 ddagent ddagent',
    'postrotate' => ['service datadog-agent restart']
  }
  # TODO: check if this is needed
  node.default['logrotate']['global']['/var/log/datadog/*.log.1'] = {
    'create' => '0600 ddagent ddagent',
    'postrotate' => ['service datadog-agent restart']
  }

  include_recipe 'datadog::dd-agent'
  include_recipe 'datadog::dd-handler'

  datadog_templates.each do |template|
    template "etc/dd-agent/conf.d/#{template}.yaml" do
      source "datadog/#{template}.yaml.erb"
      owner 'dd-agent'
      notifies :restart, 'service[datadog-agent]', :delayed
    end
  end

  cookbook_file '/opt/datadog-agent/agent/checks.d/alfSolr.py' do
    source '/datadog/agents/alfSolr.py'
    owner 'root'
    group 'root'
    mode '0644'
    only_if { datadog_templates.include? 'alfSolr' }
  end

  service 'datadog-agent' do
    action :nothing
  end
end
