#!/bin/bash
set +e

TMP=$(mktemp -t foreman-selinux-enable.XXXXXXXXXX)
trap "rm -rf '$TMP'" EXIT INT TERM

is_redhat_6() {
  test x$(rpm -q --whatprovides redhat-release --qf '%{version}') = x6
}

# Load or upgrade foreman policy and set booleans.
#
# Dependant booleans must be managed in a separate transaction.
# Do not forget to edit counterpart file (disable) when updating this script.
# Remember this will be run on upgrade too.
#
for selinuxvariant in targeted
do
  if /usr/sbin/semodule -s $selinuxvariant -l >/dev/null; then
    # Load policy
    /usr/sbin/semanage module -S $selinuxvariant \
      -a /usr/share/selinux/${selinuxvariant}/foreman.pp.bz2

    echo "boolean -m --on httpd_setrlimit" > $TMP

    /usr/sbin/semanage port -E | grep -q elasticsearch_port_t || \
      echo "port -a -t elasticsearch_port_t -p tcp 9200-9300" >> $TMP

    /usr/sbin/semanage port -E | grep -q docker_port_t || \
      echo "port -a -t docker_port_t -p tcp 2375-2376" >> $TMP

    if is_redhat_6; then
      /usr/sbin/semanage port -E | grep -q foreman_osapi_compute_port_t || \
        echo "port -a -t foreman_osapi_compute_port_t -p tcp 8774" >> $TMP
    fi

    /usr/sbin/semanage -S $selinuxvariant -i $TMP
  fi
done
