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

# Install fluentd agent
windows_package 'td-agent' do
  source node['td-agent']['windows_package']
  checksum node['td-agent']['windows_package_checksum']
end

# Create directory for buffer files
directory 'c:\opt\td-agent\buffer\secure-forward-failed' do
  action :create
  recursive true
end

# Install *secure-forward* plugin
execute 'install_secure_forward_plugin' do
  command 'fluent-gem install fluent-plugin-secure-forward'
  cwd 'c:\opt\td-agent\embedded\bin'
  not_if 'fluent-gem list --local | find "fluent-plugin-secure-forward"'
end

# Create directory for configuration files
directory 'c:\opt\td-agent\conf\conf.d' do
  action :create
  recursive true
end

file 'c:\opt\td-agent\conf\td-agent.conf' do
  content '@include conf.d/*.conf'
end

# Create directory for log files
directory 'c:\opt\td-agent\logs' do
  action :create
end

# Configure certificate file
file node['fluentd']['ca_cert_windows_path'] do
  content node['fluentd']['ca_cert']
end

# Create windows service for fluentd
batch 'create_fluentd_service' do
  code <<-EOH
    fluentd --reg-winsvc i & fluentd --reg-winsvc-fluentdopt "-c C:/opt/td-agent/conf/td-agent.conf -o C:/opt/td-agent/logs/td-agent.log"
  EOH
  cwd 'c:\opt\td-agent\embedded\bin'
  notifies :configure_startup, 'windows_service[fluentdwinsvc]', :delayed
  not_if 'SC QUERY fluentdwinsvc'
end

# Configure match
fluentd_shared_key = data_bag_item('secrets', 'fluentd_secret_data')
shared_key = fluentd_shared_key['shared_key'].chomp
template 'c:/opt/td-agent/conf/conf.d/secure_forward.conf' do
  source 'secure_forward.conf.erb'
  variables ({
    fluentd_shared_key: shared_key,
  })
  notifies :restart, 'windows_service[fluentdwinsvc]', :delayed
end

# Fluentd service
windows_service 'fluentdwinsvc' do
  supports start: true, restart: true, stop: true, configure_startup: true
  action :nothing
  startup_type :automatic
end
