#!/bin/sh

# Detect if being run as a user service, which implies external session management,
# exec compositor directly
if [ -n "${MANAGERPID:-}" ] && [ "${SYSTEMD_EXEC_PID:-}" = "$$" ]; then
    case "$(ps -p "$MANAGERPID" -o cmd=)" in
    *systemd*--user*)
        exec niri --session
        ;;
    esac
fi

if [ -n "$SHELL" ] &&
   grep -q "$SHELL" /etc/shells &&
   ! (echo "$SHELL" | grep -q "false") &&
   ! (echo "$SHELL" | grep -q "nologin"); then
  if [ "$1" != '-l' ]; then
    exec "$SHELL" -l -c "exec $0 -l $*"
  else
    shift
  fi
fi

# Try to detect the service manager that is being used
if hash systemctl >/dev/null 2>&1; then
    # Make sure there's no already running session.
    if systemctl --user -q is-active niri.service; then
      echo 'A niri session is already running.'
      exit 1
    fi

    # Reset failed state of all user units.
    systemctl --user reset-failed

    # Import the login manager environment.
    #
    # We intentionally import *all* environment variables.
    # It's unfortunately commonplace for distros to initialize
    # things with shell scripts and set environment variables.
    #
    # For example, debuginfod is initialized this way, and sets the
    # $DEBUGINFOD_URLS environment variable. If we don't export it,
    # then programs started from a systemd service (e.g. from xdg-autostart)
    # will be unable to use debuginfod.
    #
    # We cannot possibly know and list all variables like this, so
    # we import all of them into the environment. This also covers
    # any variables the user may have customized, such as $PATH.
    if hash dbus-update-activation-environment 2>/dev/null; then
        # The `--systemd` flag also sets the variables for systemd user services,
        # so we don't need a separate `systemctl --user import-environment` call.
        #
        # (This also avoids the deprecation warning printed by
        # a blanket `systemctl --user import-environment` that
        # some people find very annoying.)
        dbus-update-activation-environment --systemd --all
    else
        systemctl --user import-environment
    fi

    # Start niri and wait for it to terminate.
    systemctl --user --wait start niri.service

    # Force stop of graphical-session.target.
    systemctl --user start --job-mode=replace-irreversibly niri-shutdown.target

    # Unset environment that we've set.
    systemctl --user unset-environment WAYLAND_DISPLAY DISPLAY XDG_SESSION_TYPE XDG_CURRENT_DESKTOP NIRI_SOCKET
elif hash dinitctl >/dev/null 2>&1; then
    # Check that the user dinit daemon is running
    if ! pgrep -u "$(id -u)" dinit >/dev/null 2>&1; then
      echo "dinit user daemon is not running."
      exit 1
    fi

    # Make sure there's no already running session.
    if dinitctl --quiet --user is-started niri 2>/dev/null; then
      echo 'A niri session is already running.'
      exit 1
    fi

    # Import the login manager environment into dinit
    # Might not work correctly for multiline variable names, but
    # it is reasonable to assume there are none
    awk 'BEGIN{for(v in ENVIRON) if (v != "AWKPATH" && v != "AWKLIBPATH") print v}' 2>/dev/null | xargs dinitctl --quiet --user setenv 2>/dev/null

    # Usually the dbus service would start as niri's dependency and inherit
    # environment from dinit, but in case it has already started we need
    # to update its environment.
    if hash dbus-update-activation-environment >/dev/null 2>&1; then
        dbus-update-activation-environment --all >/dev/null 2>&1
    fi

    # Create the directory for the logfile, if doesn't exist
    mkdir --parents "$HOME/.local/share/niri"
    # Start niri
    dinitctl --quiet --user start niri.target 2>&1

    # Wait for termination
    dinit-monitor --user --initial -c 'sh -c "
        if [ "%s" = "stopped" ] || [ "%s" = "failed" ]; then
            ppid=$(ps -o ppid= -p $$)
            kill "$ppid"
        fi"' niri >/dev/null 2>&1

    # Unset environment that we've set.
    dinitctl --quiet --user unsetenv WAYLAND_DISPLAY DISPLAY XDG_SESSION_TYPE XDG_CURRENT_DESKTOP NIRI_SOCKET 2>/dev/null
else
    echo "No systemd or dinit detected, please use niri --session instead."
fi
