#!/bin/sh

# bakawm-session - Start bakawm as a desktop session
# Supports: systemd, dinit, and bare TTY (no service manager)
#
# This script detects which service manager is available and starts
# bakawm accordingly. It can be used from a display manager (GDM, etc.)
# or directly from a TTY.

# 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 bakawm --session
        ;;
    esac
fi

# Run with a login shell if possible
if [ -n "$SHELL" ] &&
   grep -q "$SHELL" /etc/shells &&
   ! (echo "$SHELL" | grep -q "false") &&
   ! (echo "$SHELL" | grep -q "nologin"); then
  if [ "$1" != '-l' ]; then
    exec bash -c "exec -l '$SHELL' -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
    # ===== systemd mode =====
    # Make sure there's no already running session.
    if systemctl --user -q is-active bakawm.service; then
      echo 'A bakawm session is already running.'
      exit 1
    fi

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

    # Import the login manager environment.
    systemctl --user import-environment

    # DBus activation environment is independent from systemd. While most of
    # dbus-activated services are already using `SystemdService` directive, some
    # still don't and thus we should set the dbus environment with a separate
    # command.
    if hash dbus-update-activation-environment 2>/dev/null; then
        dbus-update-activation-environment --all
    fi

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

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

    # Unset environment that we've set.
    systemctl --user unset-environment WAYLAND_DISPLAY DISPLAY XDG_SESSION_TYPE XDG_CURRENT_DESKTOP

elif hash dinitctl >/dev/null 2>&1; then
    # ===== dinit mode =====
    # 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 bakawm 2>/dev/null; then
      echo 'A bakawm session is already running.'
      exit 1
    fi

    # Import the login manager environment into dinit
    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 bakawm'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 -p "$HOME/.local/share/bakawm"

    # Start bakawm
    dinitctl --quiet --user start bakawm.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"' bakawm >/dev/null 2>&1

    # Unset environment that we've set.
    dinitctl --quiet --user unsetenv WAYLAND_DISPLAY DISPLAY XDG_SESSION_TYPE XDG_CURRENT_DESKTOP 2>/dev/null

else
    # ===== No service manager (bare TTY) mode =====
    # This works on Void Linux, Alpine Linux, Artix Linux (without dinit), etc.
    #
    # We start bakawm directly with --session, which handles:
    # - Setting XDG_CURRENT_DESKTOP and XDG_SESSION_TYPE
    # - Updating D-Bus activation environment
    # - Auto-detecting the backend (udev on TTY, winit in graphical session)

    # Update D-Bus activation environment if dbus is available
    if hash dbus-update-activation-environment 2>/dev/null; then
        dbus-update-activation-environment --all >/dev/null 2>&1
    fi

    # Start bakawm directly
    exec bakawm --session
fi