#!/usr/bin/bash
# No policy is loaded here. PID 1 loads it from the verified root on re-exec,
# before starting host services, and relabels the API filesystems at that point.
set -euo pipefail

sysroot=${1:-/sysroot}
cmdline=$(</proc/cmdline)
case " ${cmdline} " in
    *" selinux=0 "*) exit 0 ;;
esac

[[ -r ${sysroot}/etc/selinux/config ]] || {
    echo "image boot: verified root has no SELinux configuration" >&2
    exit 1
}

# Query the verified root's file-context mappings
root_context=$(chroot "${sysroot}" /usr/sbin/matchpathcon -N -n /)
[[ ${root_context} == *:*:*:* && ${root_context} != *$'\n'* ]] || {
    echo "image boot: root policy returned an invalid root-directory context" >&2
    exit 1
}

chcon -- "${root_context}" "${sysroot}"

# Repart can create these writable mountpoints before policy is loaded. Label
# only the directory inodes, never scan users' data on ordinary boots.
for path in bin sbin lib lib64 home root var tmp opt srv media mnt .system; do
    target=${sysroot}/${path}
    [[ -d ${target} || -L ${target} ]] || continue
    mountpoint -q "${target}" && continue
    context=$(chroot "${sysroot}" /usr/sbin/matchpathcon -N -n "/${path}")
    chcon -h -- "${context}" "${target}"
done

case " ${cmdline} " in
    *" image.installer=yes "*)
        # TIK queues volatile /etc and /usr overlay relabeling through native
        # /run/systemd/relabel-extra.d/ for AFTER policy loading. Pre-policy
        # chcon/setfiles labels on tmpfs would be lost at initialization.
        # Only persistent Btrfs state directory inodes are handled here.
        chroot "${sysroot}" /usr/bin/bash -euo pipefail -c '
            # Label the state directory inodes, preserving all migration data.
            for path in /var/lib /var/lib/tik /var/lib/tik/mig /var/lib/tik/log; do
                [[ -d ${path} ]] || continue
                context=$(matchpathcon -N -n "${path}")
                chcon -- "${context}" "${path}"
            done
        '
        ;;
esac
