if platform_family?('debian')
  execute 'selinux-activate' do
    command 'selinux-activate'
    action :nothing
  end
end

selinux_state 'permissive' do
  automatic_reboot true
  action :permissive
  only_if { `getenforce`.strip.downcase == 'disabled' }
end

if platform_family?('debian')
  selinux_enable_bools = %w(
    allow_execmem
    systemd_tmpfiles_manage_all
  )

  selinux_enable_bools.each do |name|
    selinux_boolean name do
      value true
      not_if { `getenforce`.strip.downcase == 'disabled' }
    end
  end

  se_dir = '/var/lib/selinux-custom-modules'

  directory "#{se_dir}" do
    owner 'root'
    group 'root'
    mode '0700'
    action :create
  end

  semodule_custom_modules = %w(
    custom_cron_policy
  )

  command_template = 'checkmodule -M -m -o %s.mod %s.te && semodule_package -o %s.pp -m %s.mod && semodule -i %s.pp'

  semodule_custom_modules.each do |file_name|
    semodule_filepath_base = "#{se_dir}/#{file_name}"
    cookbook_file "#{semodule_filepath_base}.te" do
      source "#{file_name}.te"
      owner 'root'
      group 'root'
      mode '0600'
      notifies :run, "execute[notify_change_#{file_name}]", :immediately
    end

    command_to_execute = format(command_template, semodule_filepath_base, semodule_filepath_base, semodule_filepath_base, semodule_filepath_base, semodule_filepath_base)

    execute "notify_change_#{file_name}" do
      command command_to_execute
      action :nothing
    end
  end
end

# Not enforcing until it has been made to work reliably
# selinux_state 'enforcing' do
#   automatic_reboot true
#   action :enforcing
#   only_if { `getenforce`.strip.downcase == 'permissive' }
# end
