# TODO: This should go into chef-genius
#
server_ip = node['rsyslog']['server_ip']
pem_certificate = node['rsyslog']['pem_certificate']
pem_path = node['rsyslog']['pem_path']

lines_to_append = if pem_certificate
                    [
                      ["$DefaultNetstreamDriverCAFile #{pem_path}/#{pem_certificate}", '$DefaultNetstreamDriverCAFile'],
                      ['$DefaultNetstreamDriver gtls # use gtls netstream driver', '$DefaultNetstreamDriver'],
                      ['$ActionSendStreamDriverMode 1 # require TLS for the connection', '$ActionSendStreamDriverMode'],
                      ['$ActionSendStreamDriverAuthMode anon # server is NOT authenticated', '$ActionSendStreamDriverAuthMode'],
                      ["*.* @@#{server_ip}", '@@']
                    ]
                  else
                    ["*.* @@#{server_ip}", '@@']
                  end

lines_to_append.each do |line|
  new_line = line[0]
  line_match = line[1]

  line_match = new_line if line_match.nil?

  replace_or_add "rsyslog-conf-#{line}" do
    path '/etc/rsyslog.conf'
    pattern line_match
    line new_line
    notifies :restart, 'service[rsyslog]', :delayed
  end
end

ruby_block 'insert_line' do
  block do
    file = Chef::Util::FileEdit.new('/etc/rsyslog.conf')
    file.insert_line_after_match('$ModLoad imjournal', '$ModLoad imfile')
    file.write_file
  end
end

service 'rsyslog' do
  action :nothing
end
