oink_conf_entries = node['snort']['oinkmaster']['conf_entries']
local_sniffing_conf = node['snort']['oinkmaster']['local_sniffing_conf']
oink_rules = node['snort']['oinkmaster']['rules']
download_oink_rules = node['snort']['oinkmaster']['download_rules']
start_snort = node['snort']['start_snort']
use_default_oinkmaster_conf = node['snort']['use_default_oinkmaster_conf']

node.default['logrotate']['global']['/var/log/snort/oinkmaster.log'] = {
  'create' => '0600 snort snort',
  'weekly' => false,
  'daily' => true
}
node.default['logrotate']['global']['/var/log/snort/eth0/alert'] = {
  'create' => '0600 snort snort',
  'weekly' => false,
  'daily' => true
}
node.default['logrotate']['global']['/var/log/snort/lo/alert'] = {
  'create' => '0600 snort snort',
  'weekly' => false,
  'daily' => true
}

# Add lo interface to snif
if node['snort']['oinkmaster']['local_sniffing_enabled']
  node.default['snort']['interface'] = "#{node.default['snort']['interface']} lo"
  node.default['snort']['packet_checksumming'] = '-k none'
end

template '/etc/oinkmaster.conf' do
  source 'snort/oinkmaster.conf.erb'
  mode   0644
  only_if { use_default_oinkmaster_conf }
end

if node['snort']['oinkmaster']['local_sniffing_enabled']
  local_sniffing_conf.each do |conf_entry|
    file_append "oinkmaster-conf-#{conf_entry}" do
      path '/etc/oinkmaster.conf'
      line conf_entry
      not_if "cat /etc/oinkmaster.conf | grep '#{conf_entry}'"
      notifies :restart, 'service[snortd]', :delayed
    end
  end
end

oink_conf_entries.each do |conf_entry|
  file_append "oinkmaster-conf-#{conf_entry}" do
    path '/etc/oinkmaster.conf'
    line conf_entry
    not_if "cat /etc/oinkmaster.conf | grep '#{conf_entry}'"
    notifies :restart, 'service[snortd]', :delayed
  end
end

if download_oink_rules
  oink_rules.each do |oink_rule|
    remote_file oink_rule['path'] do
      source oink_rule['url']
      notifies :restart, 'service[snortd]', :delayed
    end
  end
end

cookbook_file '/etc/snort/rules/local.rules' do
  source 'snort/local.rules'
  mode   0644
end

directory '/etc/cron.d' do
  action :create
end

cookbook_file '/etc/cron.d/snort' do
  source 'snort/snort.cron'
  owner  'root'
  group  'root'
  mode   0644
end

template '/etc/snort/snort.conf' do
  source 'snort/snort.conf.erb'
  mode   0644
end

template '/etc/sysconfig/snort' do
  source 'snort/snort.sysconfig.erb'
  mode   0644
end

template '/etc/init.d/snortd' do
  source 'snort/snortd.init.erb'
  mode   0755
end

service 'snortd' do
  action :nothing
  only_if { start_snort }
end
