if !node['ec2']['instance_id'].nil? && platform_family?('rhel')
  semodule_filename_base = 'firewalld_cloudinit'
  semodule_filepath_base = "#{Chef::Config[:file_cache_path]}/#{semodule_filename_base}"
  semodule_filepath = "#{semodule_filepath_base}.te"
  cookbook_file semodule_filepath do
    source "#{semodule_filename_base}.te"
    owner 'root'
    group 'root'
    mode '0600'
    notifies :run, "execute[semodule-install-#{semodule_filename_base}]", :immediately
  end

  execute "semodule-install-#{semodule_filename_base}" do
    command "/usr/bin/checkmodule -M -m #{semodule_filepath_base}.te -o #{semodule_filepath_base}.mod && /usr/bin/semodule_package -o #{semodule_filepath_base}.pp -m #{semodule_filepath_base}.mod && /usr/sbin/semodule -i #{semodule_filepath_base}.pp"
    action :nothing
  end
end

# Make sure the firewall is installed and enabled
firewall 'default' do
  action :install
end

# Firewall rules
firewall_rule 'ssh' do
  port 22
  command :allow
end

if node['neo4j']['config']['dbms.connector.bolt.enabled'] == 'true'
  firewall_rule 'neo4j_bolt' do
    port node['neo4j']['config']['bolt']['port']
    protocol :tcp
    command :allow
  end
end

if node['neo4j']['config']['dbms.connector.https.enabled'] == 'true'
  firewall_rule 'neo4j_https' do
    port node['neo4j']['config']['https']['port']
    protocol :tcp
    command :allow
  end
end

if node['neo4j']['config']['dbms.backup.enabled'] == 'true'
  firewall_rule 'neo4j_backup' do
    port node['neo4j']['config']['backup']['port']
    protocol :tcp
    command :allow
  end
end

if node['neo4j']['config']['dbms.routing.enabled'] == 'true'
  firewall_rule 'neo4j_routing' do
    port node['neo4j']['config']['routing']['port']
    protocol :tcp
    command :allow
  end
end

if node['neo4j']['config']['causal_clustering.enabled'] == 'true'
  firewall_rule 'neo4j_causal_clustering' do
    port [
           node['neo4j']['config']['causal_clustering.discovery_port'],
           node['neo4j']['config']['causal_clustering.transaction_port'],
           node['neo4j']['config']['causal_clustering.raft_port'],
         ]
    protocol :tcp
    command :allow
  end
end
