#!/bin/sh
set -e

# Detect if running on a Live system where service start should be skipped
is_live_system() {
  # Check common Live system indicators
  grep -q 'boot=live' /proc/cmdline 2>/dev/null && return 0
  grep -q 'rd.live' /proc/cmdline 2>/dev/null && return 0
  [ -d /run/live ] && return 0
  [ -f /.live-installer ] && return 0
  # Check if running in a container (dracut/systemd-nspawn)
  systemd-detect-virt -c -q 2>/dev/null && return 0
  return 1
}

SELINUX_SRC_DIR="/usr/share/selinux/packages/himmelblaud"
SELINUX_MAKEFILE="/usr/share/selinux/devel/Makefile"

if command -v selinuxenabled >/dev/null 2>&1 && selinuxenabled; then
  # Check if SELinux development tools are available
  if [ ! -f "$SELINUX_MAKEFILE" ]; then
    echo "Warning: SELinux development Makefile not found at $SELINUX_MAKEFILE"
    echo "Please install selinux-policy-devel and re-run this script"
    exit 0
  fi

  # Compile the policy module from source
  if [ -d "$SELINUX_SRC_DIR" ]; then
    echo "Compiling SELinux policy module..."
    cd "$SELINUX_SRC_DIR"
    if make -f "$SELINUX_MAKEFILE" himmelblaud.pp; then
      echo "Installing SELinux policy module..."
      if semodule -i himmelblaud.pp; then
        # Clean up compiled files (keep source for potential recompilation)
        rm -f himmelblaud.pp tmp/*.* 2>/dev/null || :
        rmdir tmp 2>/dev/null || :

        # Relabel installed binaries
        restorecon -Fv /usr/sbin/himmelblaud /usr/sbin/himmelblaud_tasks 2>/dev/null || :

        # Relabel existing dirs (may not exist on fresh install)
        [ -d /etc/himmelblau ]                && restorecon -RFv /etc/himmelblau || :
        [ -d /run/himmelblaud ]               && restorecon -RFv /run/himmelblaud || :
        [ -d /var/run/himmelblaud ]           && restorecon -RFv /var/run/himmelblaud || :
        [ -d /var/cache/private/himmelblaud ] && restorecon -RFv /var/cache/private/himmelblaud || :
        [ -d /var/cache/himmelblaud ]         && restorecon -RFv /var/cache/himmelblaud || :
        [ -d /var/cache/nss-himmelblau ]      && restorecon -RFv /var/cache/nss-himmelblau || :
        [ -d /var/lib/private/himmelblaud ]   && restorecon -RFv /var/lib/private/himmelblaud || :
        [ -d /var/lib/himmelblaud ]           && restorecon -RFv /var/lib/himmelblaud || :

        # Restart daemons now that the policy is loaded (if present)
        if [ -z "$DPKG_ROOT" ] && [ -d /run/systemd/system ] && ! is_live_system; then
          systemctl daemon-reload >/dev/null 2>&1 || :
          systemctl restart himmelblaud.service himmelblaud-tasks.service >/dev/null 2>&1 || :
        fi

        echo "SELinux policy module installed successfully"
      else
        echo "Warning: Failed to install SELinux policy module"
      fi
    else
      echo "Warning: Failed to compile SELinux policy module"
    fi
  else
    echo "Warning: SELinux source directory not found at $SELINUX_SRC_DIR"
  fi
fi

exit 0
