#!/bin/bash
SOURCE="$0"
#  Tool to switch between SystemD and OpenRC init systems on Debian (Trixie)
#  Created for Elive / Debian Trixie systems.

set -e
# set -x

# Source Elive functions if available
if [[ -f /usr/lib/elive-tools/functions ]]; then
    source /usr/lib/elive-tools/functions
fi
if [[ -f /usr/bin/gettext.sh ]]; then
    source /usr/bin/gettext.sh
fi

TEXTDOMAIN="elive-init-switcher"
export TEXTDOMAIN

if ((is_bookworm)) ; then
    echo "Error: This tool is not compatible with this version of Elive / Debian (bookworm or lower). You must upgrade your distribution first." >&2
    exit 1
fi

# Defaults
ASSUME_YES=0
VERBOSE=0
MIN_OPENRC_VERSION="0.53"

show_help() {
    cat << EOF
Usage: $(basename "$0") [OPTION] <openrc|systemd>

Tool to switch between SystemD and OpenRC init systems on Debian / Elive Trixie.

Commands:
  openrc                   Replace SystemD with OpenRC
  systemd                  Replace OpenRC with SystemD

Options:
  -y, --yes                Non-interactive mode, automatically answer yes to prompts
  -v, --verbose            Enable verbose output
  -h, --help               Display this help message and exit

Examples:
  $(basename "$0") openrc
  $(basename "$0") systemd -y
EOF
}

check_root() {
    if [[ "$EUID" -ne 0 ]]; then
        echo "Error: This tool must be run as root. Use 'sudo $(basename "$SOURCE")'" >&2
        exit 1
    fi
}

set_rc_conf_var() {
    local key="$1" val="$2" file="${3:-/etc/rc.conf}"
    [[ -f "$file" ]] || return 0

    if grep -qE "^[[:space:]]*#?[[:space:]]*${key}=" "$file"; then
        sed -i "0,/^[[:space:]]*#\?[[:space:]]*${key}=/s|^[[:space:]]*#\?[[:space:]]*${key}=.*|${key}=\"${val}\"|" "$file"
        local line_num
        line_num=$(grep -nE "^[[:space:]]*${key}=" "$file" | head -n 1 | cut -d: -f1)
        if [[ -n "$line_num" ]]; then
            sed -i "${line_num}!{/^[[:space:]]*#\?[[:space:]]*${key}=/d}" "$file"
        fi
    else
        echo "${key}=\"${val}\"" >> "$file"
    fi
}

get_installed_pkgs() {
    local pattern
    for pattern in "$@"; do
        dpkg-query -W -f='${db:Status-Abbrev} ${Package}\n' "$pattern" 2>/dev/null | awk '$1 ~ /^i/ {print $2}'
    done | sort -u
}

show_reboot_message() {
    local init_name="$1"
    echo "======================================================================"
    echo " ${init_name} installation complete!"
    echo " Please reboot your system immediately to start using ${init_name}."
    echo ""
    echo " Note: Since init packages were swapped on a running system,"
    echo " services should be stopped cleanly before rebooting."
    echo "======================================================================"
    echo ""
    if [[ -n "${E_START:-}" ]]; then
        echo " Exit Enlightenment and immediately reboot by running this command:"
        echo ""
        echo "   ( for file in /etc/rc0.d/K*; do [ -e \"\$file\" ] || continue ; s=\$(basename \$(readlink \"\$file\" 2>/dev/null || echo \"\$file\")) ; [ -x \"/etc/init.d/\$s\" ] && /etc/init.d/\$s stop 2>/dev/null || true ; done ; sync ; enlightenment_remote -exit 2>/dev/null || true ; sleep 2 ; sync ; reboot -f ; echo 1 > /proc/sys/kernel/sysrq 2>/dev/null || true ; echo b > /proc/sysrq-trigger 2>/dev/null || true ) &"
    else
        echo " Reboot immediately by running this command:"
        echo ""
        echo "   ( for file in /etc/rc0.d/K*; do [ -e \"\$file\" ] || continue ; s=\$(basename \$(readlink \"\$file\" 2>/dev/null || echo \"\$file\")) ; [ -x \"/etc/init.d/\$s\" ] && /etc/init.d/\$s stop 2>/dev/null || true ; done ; sync ; reboot -f ; echo 1 > /proc/sys/kernel/sysrq 2>/dev/null || true ; echo b > /proc/sysrq-trigger 2>/dev/null || true ) &"
    fi
    echo ""
    echo "======================================================================"

    # do not show the warning of shutdown forced
    rm -f /var/tmp/elivehealth/elive-system-running /var/tmp/elivehealth/elive-system-shutdown-forced

    do_reboot() {
        echo "Rebooting system..."
        local reboot_cmd
        if [[ -n "${E_START:-}" ]]; then
            reboot_cmd='( for file in /etc/rc0.d/K*; do [ -e "$file" ] || continue ; s=$(basename $(readlink "$file" 2>/dev/null || echo "$file")) ; [ -x "/etc/init.d/$s" ] && /etc/init.d/$s stop 2>/dev/null || true ; done ; sync ; enlightenment_remote -exit 2>/dev/null || true ; sleep 2 ; sync ; reboot -f ; echo 1 > /proc/sys/kernel/sysrq 2>/dev/null || true ; echo b > /proc/sysrq-trigger 2>/dev/null || true ) &'
        else
            reboot_cmd='( for file in /etc/rc0.d/K*; do [ -e "$file" ] || continue ; s=$(basename $(readlink "$file" 2>/dev/null || echo "$file")) ; [ -x "/etc/init.d/$s" ] && /etc/init.d/$s stop 2>/dev/null || true ; done ; sync ; reboot -f ; echo 1 > /proc/sys/kernel/sysrq 2>/dev/null || true ; echo b > /proc/sysrq-trigger 2>/dev/null || true ) &'
        fi
        echo "Executing: $reboot_cmd"
        eval "$reboot_cmd"
    }

    if [[ "$ASSUME_YES" -ne 0 ]]; then
        do_reboot
    else
        echo ""
        read -rp "Do you want to reboot the system now? [y/N] " confirm_reboot
        if [[ "$confirm_reboot" =~ ^[Yy]$ ]]; then
            do_reboot
        fi
    fi
}

get_current_init() {
    if [[ -d /run/systemd/system ]]; then
        echo "systemd"
    elif [[ -f /run/openrc/softlevel ]] || [[ -d /run/openrc ]]; then
        echo "openrc"
    elif [[ -f /proc/1/comm ]] && grep -q "openrc" /proc/1/comm; then
        echo "openrc"
    elif [[ -f /proc/1/comm ]] && grep -q "systemd" /proc/1/comm; then
        echo "systemd"
    elif [[ -f /sbin/init ]] && [[ "$(readlink -f /sbin/init)" == *"sysvinit"* ]]; then
        echo "sysvinit"
    else
        # Inspect PID 1 or installed package
        if dpkg -l systemd-sysv 2>/dev/null | grep -q "^ii"; then
            echo "systemd"
        elif dpkg -l openrc 2>/dev/null | grep -q "^ii"; then
            echo "openrc"
        else
            echo "unknown"
        fi
    fi
}


disable_psd_for_users() {
    if ! command -v elive-browsers-on-ram >/dev/null 2>&1; then
        return 0
    fi

    echo "--> Checking and disabling Browsers in RAM (psd) for active user profiles..."
    local browser_bins=("google-chrome" "chromium" "firefox" "firefox-esr" "palemoon" "midori" "opera" "vivaldi")

    while IFS=: read -r username _ uid _ _ homedir shell; do
        [[ "$uid" -ge 1000 && "$uid" -lt 65534 ]] || continue
        [[ -d "$homedir" ]] || continue

        if [[ -f "$homedir/.config/psd/psd.conf" ]] || [[ -d "$homedir/.config/psd" ]]; then
            echo "--> Disabling browsers on RAM for user '$username'..."

            # Gracefully close and ensure browsers are terminated for user
            for b in "${browser_bins[@]}"; do
                pkill -u "$uid" -x "$b" 2>/dev/null || true
            done
            sync

            local count=0
            while true; do
                local any_running=0
                for b in "${browser_bins[@]}"; do
                    if pgrep -u "$uid" -x "$b" >/dev/null 2>&1; then
                        any_running=1
                        break
                    fi
                done
                if [[ "$any_running" -eq 0 ]] || [[ "$count" -ge 10 ]]; then
                    break
                fi
                sleep 1
                count=$((count + 1))
            done

            for b in "${browser_bins[@]}"; do
                pkill -9 -u "$uid" -x "$b" 2>/dev/null || true
            done
            sync

            # Run elive-browsers-on-ram as the user to disable profile-sync-daemon and sync RAM back to disk
            local xdg_dir="/run/user/${uid}"
            if [[ -d "$xdg_dir" ]]; then
                su - "$username" -c "export XDG_RUNTIME_DIR='$xdg_dir'; elive-browsers-on-ram --quiet disable" 2>/dev/null || true
            else
                su - "$username" -c "elive-browsers-on-ram --quiet disable" 2>/dev/null || true
            fi
        fi
    done < /etc/passwd
}

switch_to_openrc() {
    check_root
    local current_init
    current_init="$(get_current_init)"

    local already_running=0
    if [[ "$current_init" == "openrc" ]] && ! dpkg -l systemd-sysv 2>/dev/null | grep -q "^ii"; then
        already_running=1
        echo "=================================================="
        echo " OpenRC is already the active init system."
        echo " Verifying and configuring OpenRC settings and services..."
        echo "=================================================="
    else
        echo "=================================================="
        echo " Preparing to replace SystemD with OpenRC..."
        echo "=================================================="
    fi

    if [[ "$already_running" -eq 1 ]]; then
        if [[ "$ASSUME_YES" -eq 0 ]]; then
            read -rp "Re-verify and apply OpenRC configuration? [Y/n] " confirm
            if [[ "$confirm" =~ ^[Nn]$ ]]; then
                echo "Aborted."
                exit 0
            fi
        fi
    else
        if [[ "$ASSUME_YES" -eq 0 ]]; then
            echo " Please close all open applications and save your work before proceeding,"
            echo " as a system reboot will be required after switching the init system."
            echo ""
            read -rp "Are you sure you want to replace SystemD with OpenRC? [y/N] " confirm
            if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
                echo "Aborted."
                exit 0
            fi
        fi
    fi

    # Disable Browsers on RAM for users while systemd user services are still running
    disable_psd_for_users

    export DEBIAN_FRONTEND=noninteractive
    export DEBCONF_NONINTERACTIVE_SEEN=true
    export DEBCONF_NOWARNINGS=true
    export DEBIAN_PRIORITY=critical
    export SYSTEMD_OFFLINE=1
    export UCF_FORCE_CONFFOLD=1
    export APT_LISTCHANGES_FRONTEND=none
    export TERM=linux

    # Temporary policy-rc.d to prevent invoke-rc.d/maintainer scripts from stopping/restarting daemons
    local policy_rc_created=0
    local policy_rc_backed_up=0
    if [[ -f /usr/sbin/policy-rc.d ]]; then
        cp -a /usr/sbin/policy-rc.d /usr/sbin/policy-rc.d.switcher_bak
        policy_rc_backed_up=1
    fi
    cat << 'EOF' > /usr/sbin/policy-rc.d
#!/bin/sh
exit 101
EOF
    chmod +x /usr/sbin/policy-rc.d
    policy_rc_created=1

    # Reset failed systemd units and clean up stale locks in /run/lock
    echo "--> Resetting failed units and cleaning stale lock files..."
    if command -v systemctl >/dev/null 2>&1; then
        systemctl reset-failed 2>/dev/null || true
    fi
    rm -rf /run/lock/* 2>/dev/null || true

    # Temporarily replace commands with /bin/true to prevent maintainer scripts from stopping daemons
    local stubbed_cmds=()
    for cmd in invoke-rc.d killall pkill loginctl elogind systemctl telinit; do
        local cmd_path=""
        if command -v "$cmd" >/dev/null 2>&1; then
            cmd_path="$(command -v "$cmd")"
        else
            for dir in /usr/bin /bin /usr/sbin /sbin; do
                if [[ -f "${dir}/${cmd}" ]]; then
                    cmd_path="${dir}/${cmd}"
                    break
                fi
            done
        fi

        if [[ -n "$cmd_path" ]] && [[ -f "$cmd_path" ]]; then
            if [[ ! -f "${cmd_path}.switcher_bak" ]]; then
                cp -a "$cmd_path" "${cmd_path}.switcher_bak"
            fi
            stubbed_cmds+=("$cmd_path")
            ln -sf /bin/true "$cmd_path"
        fi
    done

    # Temporarily move /run/systemd/system so [ -d /run/systemd/system ] evaluates to false
    local systemd_run_backed_up=0
    if [[ -d /run/systemd/system ]] || [[ -e /run/systemd/system ]]; then
        mv /run/systemd/system /run/systemd/system.switcher_bak
        systemd_run_backed_up=1
    fi

    neutralize_systemd_prerm() {
        # Neutralize systemd package prerm scripts so they don't block package removal when systemd is PID 1
        for prerm in /var/lib/dpkg/info/systemd*.prerm /var/lib/dpkg/info/libpam-systemd*.prerm /var/lib/dpkg/info/libnss-systemd*.prerm; do
            if [[ -f "$prerm" ]]; then
                cat << 'EOF' > "$prerm"
#!/bin/sh
exit 0
EOF
                chmod +x "$prerm"
            fi
        done
    }

    fix_apt_dependencies() {
        echo "--> Fixing any broken APT package dependencies..."
        neutralize_systemd_prerm
        dpkg --configure -a 2>/dev/null || true
        apt-get --fix-broken -f -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" -o Dpkg::Options::="--force-overwrite" \
            --allow-downgrades --allow-remove-essential --allow-change-held-packages \
            -o APT::Immediate-Configure=0 -o APT::Force-LoopBreak=1 install || true
    }

    cleanup_openrc_switch() {
        if [[ "$systemd_run_backed_up" -eq 1 ]]; then
            rm -rf /run/systemd/system
            if [[ -d /run/systemd/system.switcher_bak ]]; then
                mv /run/systemd/system.switcher_bak /run/systemd/system
            fi
        fi
        if [[ "$policy_rc_backed_up" -eq 1 ]] && [[ -f /usr/sbin/policy-rc.d.switcher_bak ]]; then
            mv -f /usr/sbin/policy-rc.d.switcher_bak /usr/sbin/policy-rc.d
        elif [[ "$policy_rc_created" -eq 1 ]]; then
            rm -f /usr/sbin/policy-rc.d
        fi
        for cmd_path in "${stubbed_cmds[@]}"; do
            if [[ -f "${cmd_path}.switcher_bak" ]]; then
                mv -f "${cmd_path}.switcher_bak" "$cmd_path"
            fi
        done
    }
    trap cleanup_openrc_switch EXIT INT TERM

    # Fix any pre-existing broken dependencies from previous incomplete runs before updating/installing
    echo "--> Checking and fixing existing package dependencies..."
    fix_apt_dependencies

    # Update package lists
    echo "--> Updating package indexes..."
    apt-get update

    # Verify available OpenRC candidate version
    local openrc_candidate
    openrc_candidate="$(apt-cache policy openrc 2>/dev/null | awk '/Candidate:/ {print $2}')"
    if [[ -n "$openrc_candidate" ]] && dpkg --compare-versions "$openrc_candidate" lt "$MIN_OPENRC_VERSION"; then
        echo "=================================================="
        echo " WARNING: Available OpenRC version (${openrc_candidate}) is lower than recommended (${MIN_OPENRC_VERSION})."
        echo " A minimum version of Elive Trixie must be used for full compatibility."
        echo "=================================================="
        if [[ "$ASSUME_YES" -eq 0 ]]; then
            read -rp "Do you want to continue anyway? [y/N] " confirm_ver
            if [[ ! "$confirm_ver" =~ ^[Yy]$ ]]; then
                echo "Aborted."
                exit 1
            fi
        fi
    fi

    # Fix any broken dependencies from previous incomplete runs
    fix_apt_dependencies

    local common_apt_opts=(
        -y
        -o "Dpkg::Options::=--force-confdef"
        -o "Dpkg::Options::=--force-confold"
        -o "Dpkg::Options::=--force-overwrite"
        --allow-downgrades
        --allow-remove-essential
        --allow-change-held-packages
        -o "APT::Immediate-Configure=0"
        -o "APT::Force-LoopBreak=1"
    )

    # 1. Remove problematic packages that conflict or depend heavily on systemd boot
    # Update: not needed anymore in elive trixie
    # echo "--> Removing conflicting packages..."
    # local plymouth_pkgs
    # plymouth_pkgs="$(get_installed_pkgs plymouth 'plymouth-theme*')"
    # if [[ -n "$plymouth_pkgs" ]]; then
    #     apt-get remove --purge "${common_apt_opts[@]}" $plymouth_pkgs 2>/dev/null || true
    # fi

    # Force remove systemd-sysv package first to break APT solver conflict loops
    dpkg --purge --force-depends systemd-sysv 2>/dev/null || true

    # 2. Install OpenRC and sysvinit core packages while removing SystemD packages that conflict
    echo "--> Installing OpenRC and SysVInit components..."
    local openrc_pkgs="openrc sysvinit-core sysvinit-utils policycoreutils elogind libpam-elogind orphan-sysvinit-scripts systemd-standalone-sysusers initscripts insserv libeinfo1 librc1t64 selinux-utils"
    local systemd_remove_pkgs="systemd-sysv- systemd- systemd-timesyncd- libnss-systemd- libpam-systemd- multipath-tools-"
    local glob_pkgs
    glob_pkgs="$(get_installed_pkgs 'libblockdev-mpath*' 'libblockdev-plugins-all*')"
    if [[ -n "$glob_pkgs" ]]; then
        for pkg in $glob_pkgs; do
            systemd_remove_pkgs="${systemd_remove_pkgs} ${pkg}-"
        done
    fi

    neutralize_systemd_prerm
    apt-get install -f "${common_apt_opts[@]}" $openrc_pkgs $systemd_remove_pkgs || \
        (fix_apt_dependencies && neutralize_systemd_prerm && apt-get install -f "${common_apt_opts[@]}" $openrc_pkgs $systemd_remove_pkgs) || \
        (neutralize_systemd_prerm && apt-get install -f "${common_apt_opts[@]}" $openrc_pkgs) || \
        (fix_apt_dependencies && neutralize_systemd_prerm && apt-get install -f "${common_apt_opts[@]}" $openrc_pkgs)
    fix_apt_dependencies

    # 3. Purge remaining systemd packages
    echo "--> Removing SystemD init packages..."
    local systemd_pkgs="systemd-sysv systemd systemd-timesyncd libnss-systemd libpam-systemd"
    local installed_systemd_purges
    installed_systemd_purges="$(get_installed_pkgs $systemd_pkgs)"
    if [[ -n "$installed_systemd_purges" ]]; then
        apt-get remove --purge "${common_apt_opts[@]}" $installed_systemd_purges || true
    fi

    # Clean up orphaned dependencies
    echo "--> Cleaning up unused dependencies..."
    apt-get autoremove --purge "${common_apt_opts[@]}" || true

    # 4. Configure OpenRC
    echo "--> Configuring OpenRC in /etc/rc.conf..."
    if [[ -f /etc/rc.conf ]]; then
        set_rc_conf_var "rc_parallel" "YES"
        set_rc_conf_var "rc_logger" "YES"
        set_rc_conf_var "rc_timeout" "20"
        # if grep -qs "stable-release: yes" /etc/elive-version ; then
            # set_rc_conf_var "rc_verbose" "NO"
        # else
            set_rc_conf_var "rc_verbose" "YES"
        # fi
    fi

    # Enable essential services in OpenRC runlevels
    echo "--> Enabling core OpenRC services..."
    if command -v rc-update >/dev/null 2>&1; then
        # sysinit runlevel services
        for srv in udev opentmpfiles-setup systemd-tmpfiles-setup; do
            if [[ -f "/etc/init.d/$srv" ]]; then
                rc-update add "$srv" sysinit 2>/dev/null || true
            fi
        done

        # default runlevel services
        for srv in dbus elogind networking network-manager acpid cron anacron alsa-utils bluetooth cups avahi-daemon ssh; do
            if [[ -f "/etc/init.d/$srv" ]]; then
                rc-update add "$srv" default 2>/dev/null || true
            fi
        done

        # Enable display manager in OpenRC if present
        for dm in lightdm gdm gdm3 sddm slim nodm xdm display-manager; do
            if [[ -f "/etc/init.d/$dm" ]]; then
                echo "--> Enabling display manager service ($dm) in OpenRC..."
                rc-update add "$dm" default 2>/dev/null || true
                break
            fi
        done
    fi

    # 5. Machine-id handling for non-systemd init
    echo "--> Setting up machine-id..."
    if [[ ! -s /etc/machine-id ]]; then
        if command -v dbus-uuidgen >/dev/null 2>&1; then
            dbus-uuidgen --ensure=/etc/machine-id
        elif command -v systemd-machine-id-setup >/dev/null 2>&1; then
            systemd-machine-id-setup 2>/dev/null || true
        fi
    fi
    mkdir -p /var/lib/dbus
    if [[ ! -e /var/lib/dbus/machine-id ]]; then
        ln -fs /etc/machine-id /var/lib/dbus/machine-id
    fi

    # 6. Add fstrim weekly cron job
    echo "--> Setting up fstrim cron job..."
    mkdir -p /etc/cron.weekly
    cat << 'EOF' > /etc/cron.weekly/fstrim
#!/bin/sh
if command -v fstrim >/dev/null 2>&1; then
    fstrim -a
fi
EOF
    chmod +x /etc/cron.weekly/fstrim

    # 7. Update PAM authentication configuration
    if command -v pam-auth-update >/dev/null 2>&1; then
        echo "--> Updating PAM configuration..."
        pam-auth-update --package 2>/dev/null || true
    fi

    # Update GRUB configuration if present
    if command -v update-grub >/dev/null 2>&1; then
        echo "--> Updating GRUB bootloader..."
        update-grub 2>/dev/null || true
    fi

    # 8. Install systemd-openrc-wrapper if available
    if command -v systemd-openrc-wrapper >/dev/null 2>&1; then
        echo "--> Installing systemd-openrc-wrapper..."
        systemd-openrc-wrapper --install || true
    fi

    if [[ "$already_running" -eq 1 ]]; then
        echo "=================================================="
        echo " OpenRC configuration and service verification complete!"
        echo " No system reboot is required."
        echo "=================================================="
    else
        show_reboot_message "OpenRC"
    fi
}

switch_to_systemd() {
    check_root
    local current_init
    current_init="$(get_current_init)"

    local already_running=0
    if [[ "$current_init" == "systemd" ]] && dpkg -l systemd-sysv 2>/dev/null | grep -q "^ii"; then
        already_running=1
        echo "=================================================="
        echo " SystemD is already the active init system."
        echo " Verifying and configuring SystemD settings and services..."
        echo "=================================================="
    else
        echo "=================================================="
        echo " Preparing to replace OpenRC with SystemD..."
        echo "=================================================="
    fi

    if [[ "$already_running" -eq 1 ]]; then
        if [[ "$ASSUME_YES" -eq 0 ]]; then
            read -rp "Re-verify and apply SystemD configuration? [Y/n] " confirm
            if [[ "$confirm" =~ ^[Nn]$ ]]; then
                echo "Aborted."
                exit 0
            fi
        fi
    else
        if [[ "$ASSUME_YES" -eq 0 ]]; then
            echo " Please close all open applications and save your work before proceeding,"
            echo " as a system reboot will be required after switching the init system."
            echo ""
            read -rp "Are you sure you want to replace OpenRC with SystemD? [y/N] " confirm
            if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
                echo "Aborted."
                exit 0
            fi
        fi
    fi

    export DEBIAN_FRONTEND=noninteractive
    export DEBCONF_NONINTERACTIVE_SEEN=true
    export DEBCONF_NOWARNINGS=true
    export DEBIAN_PRIORITY=critical
    export SYSTEMD_OFFLINE=1

    # Temporary policy-rc.d to prevent invoke-rc.d/maintainer scripts from stopping/restarting daemons
    local policy_rc_created=0
    local policy_rc_backed_up=0
    if [[ -f /usr/sbin/policy-rc.d ]]; then
        cp -a /usr/sbin/policy-rc.d /usr/sbin/policy-rc.d.switcher_bak
        policy_rc_backed_up=1
    fi
    cat << 'EOF' > /usr/sbin/policy-rc.d
#!/bin/sh
exit 101
EOF
    chmod +x /usr/sbin/policy-rc.d
    policy_rc_created=1

    # Temporarily replace commands with /bin/true to prevent maintainer scripts from stopping daemons
    local stubbed_cmds=()
    for cmd in invoke-rc.d killall pkill loginctl elogind telinit; do
        local cmd_path=""
        if command -v "$cmd" >/dev/null 2>&1; then
            cmd_path="$(command -v "$cmd")"
        else
            for dir in /usr/bin /bin /usr/sbin /sbin; do
                if [[ -f "${dir}/${cmd}" ]]; then
                    cmd_path="${dir}/${cmd}"
                    break
                fi
            done
        fi

        if [[ -n "$cmd_path" ]] && [[ -f "$cmd_path" ]]; then
            if [[ ! -f "${cmd_path}.switcher_bak" ]]; then
                cp -a "$cmd_path" "${cmd_path}.switcher_bak"
            fi
            stubbed_cmds+=("$cmd_path")
            ln -sf /bin/true "$cmd_path"
        fi
    done

    fix_apt_dependencies() {
        echo "--> Fixing any broken APT package dependencies..."
        dpkg --configure -a 2>/dev/null || true
        apt-get --fix-broken -f -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" -o Dpkg::Options::="--force-overwrite" \
            --allow-downgrades --allow-remove-essential --allow-change-held-packages \
            -o APT::Immediate-Configure=0 -o APT::Force-LoopBreak=1 install || true
    }

    cleanup_systemd_switch() {
        if [[ "$policy_rc_backed_up" -eq 1 ]] && [[ -f /usr/sbin/policy-rc.d.switcher_bak ]]; then
            mv -f /usr/sbin/policy-rc.d.switcher_bak /usr/sbin/policy-rc.d
        elif [[ "$policy_rc_created" -eq 1 ]]; then
            rm -f /usr/sbin/policy-rc.d
        fi
        for cmd_path in "${stubbed_cmds[@]}"; do
            if [[ -f "${cmd_path}.switcher_bak" ]]; then
                mv -f "${cmd_path}.switcher_bak" "$cmd_path"
            fi
        done
    }
    trap cleanup_systemd_switch EXIT INT TERM

    # Fix any pre-existing broken dependencies from previous incomplete runs before updating/installing
    echo "--> Checking and fixing existing package dependencies..."
    fix_apt_dependencies

    # Update package lists
    echo "--> Updating package indexes..."
    apt-get update

    # Uninstall systemd-openrc-wrapper before switching if present
    if command -v systemd-openrc-wrapper >/dev/null 2>&1; then
        echo "--> Uninstalling systemd-openrc-wrapper..."
        systemd-openrc-wrapper --uninstall --yes --purge || true
    fi
    rm -rf /var/lib/systemd-openrc-wrapper /etc/systemd-openrc-wrapper 2>/dev/null || true


    # Force remove sysvinit-core package first to break APT solver conflict loops
    dpkg --purge --force-depends sysvinit-core 2>/dev/null || true

    # Resolve any APT state inconsistencies left by force-purging dpkg packages
    fix_apt_dependencies

    # 1. Install SystemD components while removing conflicting OpenRC / SysVInit packages
    echo "--> Installing SystemD components..."
    local systemd_pkgs="systemd-sysv systemd systemd-timesyncd libnss-systemd libpam-systemd"
    local openrc_remove_pkgs="sysvinit-core- openrc- elogind- libpam-elogind- orphan-sysvinit-scripts- ntp- ntpsec- chrony-"
    local common_apt_opts=(
        -y
        -o "Dpkg::Options::=--force-confdef"
        -o "Dpkg::Options::=--force-confold"
        -o "Dpkg::Options::=--force-overwrite"
        --allow-downgrades
        --allow-remove-essential
        --allow-change-held-packages
        -o "APT::Immediate-Configure=0"
        -o "APT::Force-LoopBreak=1"
    )

    apt-get install -f "${common_apt_opts[@]}" $systemd_pkgs $openrc_remove_pkgs || \
        (fix_apt_dependencies && apt-get install -f "${common_apt_opts[@]}" $systemd_pkgs $openrc_remove_pkgs) || \
        apt-get install -f "${common_apt_opts[@]}" $systemd_pkgs || \
        (fix_apt_dependencies && apt-get install -f "${common_apt_opts[@]}" $systemd_pkgs)
    fix_apt_dependencies

    # 2. Remove OpenRC and SysVInit components
    echo "--> Removing OpenRC packages..."
    local openrc_pkgs="sysvinit-core openrc elogind libpam-elogind orphan-sysvinit-scripts"
    apt-get remove --purge "${common_apt_opts[@]}" $openrc_pkgs || true

    # Clean up orphaned dependencies
    echo "--> Cleaning up unused dependencies..."
    apt-get autoremove --purge "${common_apt_opts[@]}" || true

    # 3. Enable SystemD services
    echo "--> Enabling standard SystemD services..."
    systemctl unmask ssh.service 2>/dev/null || true
    systemctl enable ssh.service 2>/dev/null || true
    systemctl enable dbus.service 2>/dev/null || true
    systemctl enable NetworkManager.service 2>/dev/null || true
    systemctl enable systemd-timesyncd.service 2>/dev/null || true
    systemctl enable fstrim.timer 2>/dev/null || true

    # Enable display manager in SystemD
    for dm in lightdm gdm gdm3 sddm slim nodm xdm; do
        if systemctl list-unit-files 2>/dev/null | grep -q "^${dm}\.service"; then
            echo "--> Enabling display manager service (${dm}.service) in SystemD..."
            systemctl enable "${dm}.service" 2>/dev/null || true
            break
        fi
    done

    # 4. Clean up OpenRC cron fstrim
    rm -f /etc/cron.weekly/fstrim

    # 5. Ensure machine-id is configured
    if [[ ! -s /etc/machine-id ]] && command -v systemd-machine-id-setup >/dev/null 2>&1; then
        systemd-machine-id-setup 2>/dev/null || true
    fi

    # 6. Update PAM authentication configuration
    if command -v pam-auth-update >/dev/null 2>&1; then
        echo "--> Updating PAM configuration..."
        pam-auth-update --package 2>/dev/null || true
    fi

    # Update GRUB configuration if present
    if command -v update-grub >/dev/null 2>&1; then
        echo "--> Updating GRUB bootloader..."
        update-grub 2>/dev/null || true
    fi

    if [[ "$already_running" -eq 1 ]]; then
        echo "=================================================="
        echo " SystemD configuration and service verification complete!"
        echo " No system reboot is required."
        echo "=================================================="
    else
        show_reboot_message "SystemD"
    fi
}

# Parse command line options
COMMAND=""

if [[ $# -eq 0 ]]; then
    show_help
    exit 0
fi

while [[ $# -gt 0 ]]; do
    case "$1" in
        -h|--help)
            show_help
            exit 0
            ;;
        -y|--yes)
            ASSUME_YES=1
            shift
            ;;
        -v|--verbose)
            VERBOSE=1
            set -x
            shift
            ;;
        openrc)
            COMMAND="openrc"
            shift
            ;;
        systemd)
            COMMAND="systemd"
            shift
            ;;
        *)
            echo "Error: Unknown argument '$1'" >&2
            echo ""
            show_help
            exit 1
            ;;
    esac
done

case "$COMMAND" in
    openrc)
        switch_to_openrc
        ;;
    systemd)
        switch_to_systemd
        ;;
    "")
        show_help
        exit 0
        ;;
esac
