#!/bin/sh

# This systemd.generator(7) detects if SELinux is running and if the
# user requested an autorelabel. If so, services will be enabled to
# run after subvolumes and partitions are mounted before local-fs.target
# is reached.

# If invoked with no arguments (for testing) write to /tmp.
generatordir="/tmp"
if [ -n "$1" ]; then
    generatordir="$1"
fi

enable_units() {
    mkdir -p "${generatordir}"/local-fs.target.requires

    for realdir in ".snapshots" "home" "opt" "root" "srv" "usr/local" \
		"boot/grub2/i386-pc" "boot/grub2/x86_64-efi" \
		"boot/grub2/arm64-efi" "boot/writable"; do
        # Make sure the directory exist, else we create
        # services for non existing mount points
        test -d "/${realdir}" || continue
	mountunit=$(systemd-escape --path ${realdir})
	unitfile="${mountunit}-relabel.service"

	{
	    echo "[Unit]";
            echo "Description=Relabel ${realdir}";
            echo "DefaultDependencies=no";
            echo "RequiresMountsFor=/${realdir}";
            echo "Before=local-fs.target";
            echo "ConditionSecurity=selinux";
            echo "";
            echo "[Service]";
            echo "Type=oneshot";
	    case "$realdir" in
		.snapshots)
		    echo "ExecStart=/sbin/restorecon -R -x /${realdir}";
		    ;;
		*)
		    echo "ExecStart=/sbin/restorecon -R /${realdir}";
		    ;;
	    esac
	} > "${generatordir}"/"${unitfile}"

	ln -sf ../"${unitfile}" "${generatordir}"/local-fs.target.requires/"${unitfile}"
    done
}

if [ -x /usr/sbin/selinuxenabled ] && /usr/sbin/selinuxenabled; then
    if test -f /etc/selinux/.autorelabel; then
        enable_units
        rm -f /etc/selinux/.autorelabel
    elif grep -sqE "\bautorelabel\b" /proc/cmdline; then
        enable_units
    fi
fi
