#
# Cookbook:: irrigate-fluentd
# Recipe:: apache
#
# Copyright: The Orchard
#

include_recipe 'td-agent::default'

# Grant read access to apache logs and configure sources and filters for apache log files
if node['fluentd']['apache_logs'] && !node['fluentd']['apache_logs'].empty?
  logs_path = node['fluentd']['apache_logs_path']

  directory logs_path do
    mode '0755'
  end

  node['fluentd']['apache_logs'].each do |log_name, log_format|
    file "#{logs_path}/#{log_name}" do
      group node['td_agent']['group']
    end

    if log_format == 'custom_multihost'
      # Use custom regex so multiple hosts do not break built-in source
      td_agent_source "source-apache-#{log_name}" do
        type 'tail'
        tag "apache.#{log_name}"
        parameters(
          time_format: '%d/%b/%Y:%H:%M:%S %z',
          format: node['fluentd']['apache']['custom_multihost_format'],
          path: "#{logs_path}/#{log_name}"
        )
      end
    else
      # Otherwise, use built-in apache source parser
      td_agent_source "source-apache-#{log_name}" do
        type 'tail'
        tag "apache.#{log_name}"
        parameters(
          format: log_format,
          path: "#{logs_path}/#{log_name}"
        )
      end
    end

    td_agent_filter "filter-apache-#{log_name}" do
      type 'record_transformer'
      tag "apache.#{log_name}"
      parameters(
        record: [{
          host_name: node['fqdn'],
          host_ip: node['ipaddress'],
          log_type: 'apache',
          log_name: log_name,
        }]
      )
    end
  end
end
