#!/bin/bash
SOURCE="$0"
#
# systemd-openrc-wrapper -- compatibility shim that lets scripts/tools written
# for systemd (systemctl, journalctl, hostnamectl, timedatectl, localectl,
# loginctl, systemd-analyze, systemd-cat, systemd-notify, systemd-run,
# systemd-tmpfiles, systemd-sysctl, ...) run unmodified on an OpenRC system.
#
# Minimum supported OpenRC version: 0.63.3
# (this is the version shipped in Elive 3.8.60, built over Debian Trixie).
# No compatibility fallbacks are kept for older OpenRC releases -- we rely on
# features guaranteed present since 0.60/0.62, such as:
#   - `rc-service --user` / `rc-update --user` (user services, 0.60,
#     no longer experimental since 0.62)
#   - `rc-status --in-state` / `-i` (0.62)
#
# Core commands:
#   systemd-openrc-wrapper install       (or --install)
#   systemd-openrc-wrapper uninstall     (or --uninstall)
#   systemd-openrc-wrapper check-install (or --check-install)
#   systemd-openrc-wrapper test          (or --test, check-compat)
#
# Run `systemd-openrc-wrapper help` for full usage, options, and examples.
#
set -o pipefail

VERSION="3.0.0"
ORIGINAL_ARGV0="$0"
ORIGINAL_ARGV=("$@")
SCRIPT_NAME="${0##*/}"
SCRIPT_PATH="$(readlink -f "$0" 2>/dev/null || echo "$0")"
ORIGINAL_INVOCATION="$SCRIPT_NAME $*"

# ---------------------------------------------------------------------------
# Elive-tools integration
# ---------------------------------------------------------------------------
if [ -r /usr/lib/elive-tools/functions ]; then
    # shellcheck disable=SC1091
    source /usr/lib/elive-tools/functions
    EL_REPORTS="1"
else
    # Minimal stand-ins so this still works if elive-tools isn't present yet
    # (e.g. very early boot, or a non-Elive OpenRC box using this tool).
    el_info()    { echo "systemd-openrc-wrapper: [INFO] $*"    >&2; }
    el_warning() { echo "systemd-openrc-wrapper: [WARNING] $*" >&2; }
    el_error()   { echo "systemd-openrc-wrapper: [ERROR] $*"   >&2; }
    el_debug()   { [ "${SYSTEMD_OPENRC_WRAPPER_DEBUG:-0}" = "1" ] && echo "systemd-openrc-wrapper: [DEBUG] $*" >&2; return 0; }
    el_sudo()    { sudo "$@"; }
    el_check_sudo_automated() { sudo -n true 2>/dev/null; }
    el_dependencies_check() {
        local IFS='|' d
        for d in $1; do command -v "$d" &>/dev/null || return 1; done
        return 0
    }
    el_confirm() { read -r -p "$1 [y/N] " _a; [[ "$_a" =~ ^[Yy]$ ]]; }
    el_notify()  { :; }
    el_elive_version_get() { cat /etc/elive-version 2>/dev/null; }
    el_add_on_exit() { :; }
    # notify about non-elive system:
    el_warning "Not an Elive Linux system -- some features may be not working"
fi

# ---------------------------------------------------------------------------
# Config (overridable via /etc/systemd-openrc-wrapper.conf)
# ---------------------------------------------------------------------------
WRAPPER_TARGET="/bin/systemd-openrc-wrapper"
MANIFEST_DIR="/var/lib/systemd-openrc-wrapper"
MANIFEST_FILE="$MANIFEST_DIR/manifest"
BACKUP_DIR="$MANIFEST_DIR/backup"
MASK_DIR="/etc/systemd-openrc-wrapper/masks"
DEFAULT_RUNLEVEL_FILE="/etc/systemd-openrc-wrapper/default-runlevel"
VERBOSE="${SYSTEMD_OPENRC_WRAPPER_DEBUG:-0}"
QUIET_NOTICE="${SYSTEMD_OPENRC_WRAPPER_QUIET:-0}"
MIN_OPENRC_VERSION="0.63.3"

NAMES=(systemctl journalctl hostnamectl timedatectl localectl loginctl
       systemd-ac-power systemd-analyze systemd-ask-password systemd-cat
       systemd-cgls systemd-cgtop systemd-confext systemd-creds systemd-delta
       systemd-detect-virt systemd-escape systemd-firstboot systemd-hwdb
       systemd-id128 systemd-inhibit systemd-machine-id-setup systemd-mount
       systemd-notify systemd-path systemd-run systemd-socket-activate
       systemd-stdio-bridge systemd-sysext systemd-sysctl systemd-sysusers
       systemd-tmpfiles systemd-tty-ask-password-agent systemd-umount
       systemd-vpick)
BINDIRS=(/bin /usr/bin /sbin /usr/sbin)

[ -r /etc/systemd-openrc-wrapper.conf ] && source /etc/systemd-openrc-wrapper.conf

# ---------------------------------------------------------------------------
# Locate OpenRC tooling
# ---------------------------------------------------------------------------
RC_SERVICE_BIN=$(command -v rc-service 2>/dev/null)
RC_UPDATE_BIN=$(command -v rc-update 2>/dev/null)
RC_STATUS_BIN=$(command -v rc-status 2>/dev/null)
OPENRC_BIN=$(command -v openrc 2>/dev/null)

# ---------------------------------------------------------------------------
# Cleanup trap
# ---------------------------------------------------------------------------
_TMP_MANIFEST=""
_cleanup_tmp_manifest() { [ -n "$_TMP_MANIFEST" ] && rm -f "$_TMP_MANIFEST"; }
el_add_on_exit "_cleanup_tmp_manifest" 2>/dev/null
trap _cleanup_tmp_manifest EXIT 2>/dev/null

# ---------------------------------------------------------------------------
# Generic helpers
# ---------------------------------------------------------------------------
die()  { el_error "$*"; exit 1; }

# Print the "you're on OpenRC, we suggest X" notice before running $1.
notice() {
    [ "$QUIET_NOTICE" = "1" ] && return 0
    el_info "OpenRC system detected -- '$ORIGINAL_INVOCATION' translated to: '$1' (you can use the openrc method instead, or silence this message with SYSTEMD_OPENRC_WRAPPER_QUIET=1 )"
}

# Requires root; auto-elevates via el_sudo instead of failing outright.
check_root() {
    [ "$(id -u)" -eq 0 ] && return 0
    if el_check_sudo_automated &>/dev/null; then
        el_debug "Elevating privileges automatically via el_sudo (passwordless sudo available)."
    else
        el_warning "This operation requires root privileges -- you may be prompted for a password."
    fi
    exec el_sudo "$ORIGINAL_ARGV0" "${ORIGINAL_ARGV[@]}"
}

require_openrc() {
    if ! el_dependencies_check "rc-service|rc-update|rc-status|openrc"; then
        el_error "OpenRC tools (rc-service/rc-update/rc-status/openrc) not found -- is openrc >= $MIN_OPENRC_VERSION installed?"
        exit 1
    fi
}

# Strip systemd-style unit suffixes -> plain OpenRC service name.
normalize_unit() {
    local u="${1##*/}"
    for sfx in service socket timer target mount path device swap; do
        u="${u%.$sfx}"
    done
    echo "$u"
}

# Match property against filter list (handles comma-separated and multiple flags)
match_property() {
    local prop_line="$1"
    shift
    local prop_filters=("$@")
    if [ ${#prop_filters[@]} -eq 0 ]; then
        return 0
    fi
    local key="${prop_line%%=*}"
    local pf f f_arr
    for pf in "${prop_filters[@]}"; do
        IFS=',' read -r -a f_arr <<< "$pf"
        for f in "${f_arr[@]}"; do
            [ "$f" = "$key" ] && return 0
        done
    done
    return 1
}

# Loosely map well-known systemd targets to OpenRC runlevels/actions.
map_target_to_runlevel() {
    case "$1" in
        poweroff.target)                      echo "shutdown" ;;
        rescue.target|emergency.target)       echo "single"   ;;
        multi-user.target|graphical.target|default.target)
                                               echo "default"  ;;
        reboot.target)                        echo "reboot"   ;;
        *)                                     echo "$1"       ;;
    esac
}

# ---------------------------------------------------------------------------
# "mask" emulation (OpenRC has no native mask concept)
# ---------------------------------------------------------------------------
mask_file()  { echo "$MASK_DIR/$(normalize_unit "$1")"; }
is_masked()  {
    local svc; svc=$(normalize_unit "$1")
    [ -e "$MASK_DIR/$svc" ] || [ "$(readlink -f "/etc/systemd/system/${svc}.service" 2>/dev/null)" = "/dev/null" ]
}

do_mask() {
    check_root
    local svc; svc=$(normalize_unit "$1")
    mkdir -p "$MASK_DIR" /etc/systemd/system
    notice "touch $(mask_file "$svc")  &&  rc-update del $svc"
    touch "$(mask_file "$svc")"
    ln -sf /dev/null "/etc/systemd/system/${svc}.service" 2>/dev/null || true
    "$RC_UPDATE_BIN" del "$svc" &>/dev/null
    if [ "${now_flag:-0}" -eq 1 ]; then
        "$RC_SERVICE_BIN" "$svc" stop &>/dev/null || true
    fi
    echo "Masked $1."
}

do_unmask() {
    check_root
    local svc; svc=$(normalize_unit "$1")
    notice "rm -f $(mask_file "$svc")"
    rm -f "$(mask_file "$svc")"
    if [ "$(readlink -f "/etc/systemd/system/${svc}.service" 2>/dev/null)" = "/dev/null" ]; then
        rm -f "/etc/systemd/system/${svc}.service"
    fi
    echo "Unmasked $1."
}

# ===========================================================================
# systemctl
# ===========================================================================
cmd_systemctl() {
    require_openrc

    local runlevel="default" now_flag=0 quiet=0 user_mode=0 state_filter=""
    local properties=() value_only=0 all_flag=0 global_flag=0 runtime_flag=0 force_flag=0 no_legend=0
    local lines_val="" output_val="" signal_val="" kill_whom=""
    local rest=()

    while [ $# -gt 0 ]; do
        case "$1" in
            --user)                user_mode=1; shift ;;
            --system)              user_mode=0; shift ;;
            --now)                 now_flag=1; shift ;;
            -q|--quiet)            quiet=1; shift ;;
            -f|--force)            force_flag=1; shift ;;
            --failed)              state_filter="failed"; shift ;;
            --state=*)             state_filter="${1#*=}"; shift ;;
            --state)               state_filter="$2"; shift 2 ;;
            -t|--type)             shift 2 ;;
            --type=*|-t*)          shift ;;
            -p|--property)         [ $# -ge 2 ] && properties+=("$2") && shift 2 || shift ;;
            --property=*)          properties+=("${1#*=}"); shift ;;
            -p*)                   properties+=("${1#-p}"); shift ;;
            -P)                    [ $# -ge 2 ] && value_only=1 && properties+=("$2") && shift 2 || shift ;;
            -P*)                   value_only=1; properties+=("${1#-P}"); shift ;;
            --value)               value_only=1; shift ;;
            -a|--all)              all_flag=1; shift ;;
            --global)              global_flag=1; shift ;;
            --runtime)             runtime_flag=1; shift ;;
            --no-legend)           no_legend=1; shift ;;
            --legend=no|--legend=false|--legend=0) no_legend=1; shift ;;
            --legend=yes|--legend=true|--legend=1) no_legend=0; shift ;;
            -n|--lines)            [ $# -ge 2 ] && lines_val="$2" && shift 2 || shift ;;
            --lines=*|-n*)         lines_val="${1#*=}"; shift ;;
            -o|--output)           [ $# -ge 2 ] && output_val="$2" && shift 2 || shift ;;
            --output=*|-o*)        output_val="${1#*=}"; shift ;;
            -s|--signal)           [ $# -ge 2 ] && signal_val="$2" && shift 2 || shift ;;
            --signal=*|-s*)        signal_val="${1#*=}"; shift ;;
            --kill-whom=*)         kill_whom="${1#*=}"; shift ;;
            --kill-whom)           [ $# -ge 2 ] && kill_whom="$2" && shift 2 || shift ;;
            --runlevel=*)          runlevel="${1#*=}"; shift ;;
            --runlevel)            [ $# -ge 2 ] && runlevel="$2" && shift 2 || shift ;;
            --root=*|--image=*|--image-policy=*|--job-mode=*|-H*|--host=*|-M*|--machine=*|-C*|--capsule=*)
                                   shift ;;
            --root|--image|--image-policy|--job-mode|-H|--host|-M|--machine|-C|--capsule)
                                   shift 2 ;;
            --no-pager|--no-ask-password|--no-block|--no-wait|--no-wall|--no-reload|--no-warn|--plain|--mkdir|--read-only|--marked|--stdin|--firmware-setup|-i|--check-inhibitors|-l|--full|-r|--recursive|--reverse|--before|--after|--with-dependencies|-T|--show-transaction|--show-types|--legend)
                                   shift ;;
            --legend=*|--check-inhibitors=*|--what=*|--message=*|--preset-mode=*|--boot-loader-menu=*|--boot-loader-entry=*|--reboot-argument=*|--timestamp=*|--drop-in=*|--when=*|--kill-value=*)
                                   shift ;;
            --what|--message|--preset-mode|--boot-loader-menu|--boot-loader-entry|--reboot-argument|--timestamp|--drop-in|--when|--kill-value)
                                   shift 2 ;;
            --dry-run)             shift ;;
            -h|--help)             rest+=("help"); shift ;;
            --version)             rest+=("version"); shift ;;
            --)                    shift; rest+=("$@"); break ;;
            -*)                    shift ;;
            *)                     rest+=("$1"); shift ;;
        esac
    done
    set -- "${rest[@]}"

    local action="$1"; shift 2>/dev/null || true
    local units=("$@")

    # rc-service/rc-update --user is fully supported (non-experimental) since
    # OpenRC 0.62, guaranteed present at our 0.63.3 minimum.
    local rc_user_flag=()
    [ "$user_mode" -eq 1 ] && rc_user_flag=(--user)

    case "$action" in
        start|stop|restart|try-restart|reload|reload-or-restart|reload-or-try-restart|try-reload-or-restart|condrestart)
            [ ${#units[@]} -eq 0 ] && die "no unit specified for $action"
            local rc_action="$action"
            case "$action" in
                try-restart|condrestart)                              rc_action="restart" ;;
                reload-or-restart|reload-or-try-restart|try-reload-or-restart) rc_action="reload"  ;;
            esac
            [ "$user_mode" -eq 0 ] && check_root
            local overall=0 u svc
            for u in "${units[@]}"; do
                svc=$(normalize_unit "$u")
                if [[ "$action" == start || "$action" == restart ]] && is_masked "$svc"; then
                    el_error "Failed to $action $u: unit is masked."
                    overall=1; continue
                fi
                if [ "$action" = "reload" ]; then
                    notice "rc-service ${rc_user_flag[*]} $svc reload"
                    "$RC_SERVICE_BIN" "${rc_user_flag[@]}" "$svc" reload
                elif [[ "$action" == reload-or-restart || "$action" == reload-or-try-restart || "$action" == try-reload-or-restart ]]; then
                    notice "rc-service ${rc_user_flag[*]} $svc reload (or restart)"
                    "$RC_SERVICE_BIN" "${rc_user_flag[@]}" "$svc" reload 2>/dev/null \
                        || "$RC_SERVICE_BIN" "${rc_user_flag[@]}" "$svc" restart
                elif [[ "$action" == try-restart || "$action" == condrestart ]]; then
                    if "$RC_SERVICE_BIN" "${rc_user_flag[@]}" "$svc" status &>/dev/null; then
                        notice "rc-service ${rc_user_flag[*]} $svc restart"
                        "$RC_SERVICE_BIN" "${rc_user_flag[@]}" "$svc" restart
                    fi
                else
                    notice "rc-service ${rc_user_flag[*]} $svc $rc_action"
                    "$RC_SERVICE_BIN" "${rc_user_flag[@]}" "$svc" "$rc_action"
                fi
                if [ $? -ne 0 ]; then
                    overall=1
                    el_error "$action failed for $u"
                    el_notify normal "dialog-error" "Service $action failed" "$u could not be ${action}ed." 2>/dev/null
                fi
            done
            exit $overall
            ;;

        status)
            if [ ${#units[@]} -eq 0 ]; then
                if [ -n "$state_filter" ]; then
                    notice "rc-status --in-state=$state_filter"
                    exec "$RC_STATUS_BIN" "${rc_user_flag[@]}" --in-state="$state_filter"
                fi
                notice "rc-status --all"
                exec "$RC_STATUS_BIN" "${rc_user_flag[@]}" --all
            fi
            local overall=0 u svc n_lines
            n_lines="${lines_val:-10}"
            for u in "${units[@]}"; do
                svc=$(normalize_unit "$u")
                notice "rc-service ${rc_user_flag[*]} $svc status"
                "$RC_SERVICE_BIN" "${rc_user_flag[@]}" "$svc" status
                [ $? -ne 0 ] && overall=$?
                if [ "$quiet" -eq 0 ] && [ "$n_lines" -gt 0 ]; then
                    cmd_journalctl -u "$svc" -n "$n_lines" --quiet 2>/dev/null || true
                fi
            done
            exit $overall
            ;;

        enable)
            [ "$user_mode" -eq 0 ] && check_root
            local u svc
            for u in "${units[@]}"; do
                svc=$(normalize_unit "$u")
                if is_masked "$svc"; then
                    el_error "Unit $u is masked; cannot enable."
                    continue
                fi
                notice "rc-update ${rc_user_flag[*]} add $svc $runlevel"
                "$RC_UPDATE_BIN" "${rc_user_flag[@]}" add "$svc" "$runlevel"
                [ "$now_flag" -eq 1 ] && "$RC_SERVICE_BIN" "${rc_user_flag[@]}" "$svc" start
            done
            ;;

        disable)
            [ "$user_mode" -eq 0 ] && check_root
            local u svc
            for u in "${units[@]}"; do
                svc=$(normalize_unit "$u")
                notice "rc-update ${rc_user_flag[*]} del $svc"
                "$RC_UPDATE_BIN" "${rc_user_flag[@]}" del "$svc" &>/dev/null \
                    || "$RC_UPDATE_BIN" "${rc_user_flag[@]}" del "$svc" "$runlevel" &>/dev/null
                [ "$now_flag" -eq 1 ] && "$RC_SERVICE_BIN" "${rc_user_flag[@]}" "$svc" stop
            done
            ;;

        reenable)
            [ "$user_mode" -eq 0 ] && check_root
            local u svc
            for u in "${units[@]}"; do
                svc=$(normalize_unit "$u")
                notice "rc-update ${rc_user_flag[*]} del $svc && rc-update ${rc_user_flag[*]} add $svc $runlevel"
                "$RC_UPDATE_BIN" "${rc_user_flag[@]}" del "$svc" &>/dev/null
                "$RC_UPDATE_BIN" "${rc_user_flag[@]}" add "$svc" "$runlevel"
            done
            ;;

        preset|preset-all)
            [ "$user_mode" -eq 0 ] && check_root
            el_warning "$action: presets are half-emulated on OpenRC (reenabling matching services)."
            local u svc
            for u in "${units[@]}"; do
                svc=$(normalize_unit "$u")
                notice "rc-update ${rc_user_flag[*]} add $svc $runlevel"
                "$RC_UPDATE_BIN" "${rc_user_flag[@]}" add "$svc" "$runlevel" 2>/dev/null || true
            done
            ;;

        is-enabled)
            local overall=0 u svc line
            local show_out
            show_out=$("$RC_UPDATE_BIN" "${rc_user_flag[@]}" show -v 2>/dev/null)
            for u in "${units[@]}"; do
                svc=$(normalize_unit "$u")
                if is_masked "$svc"; then
                    [ "$quiet" -eq 0 ] && echo "masked"
                    overall=1
                    continue
                fi
                line=$(echo "$show_out" | sed -n "s/^[[:space:]]*${svc}[[:space:]]*|\(.*\)\$/\1/p")
                if echo "$line" | grep -qE '[A-Za-z]'; then
                    [ "$quiet" -eq 0 ] && echo "enabled"
                else
                    [ "$quiet" -eq 0 ] && echo "disabled"
                    overall=1
                fi
            done
            exit $overall
            ;;

        is-active)
            local overall=0 u svc st_out crashed_out
            crashed_out=$("$RC_STATUS_BIN" --crashed 2>/dev/null)
            for u in "${units[@]}"; do
                svc=$(normalize_unit "$u")
                notice "rc-service ${rc_user_flag[*]} $svc status"
                st_out=$("$RC_SERVICE_BIN" "${rc_user_flag[@]}" "$svc" status 2>&1 || true)
                if echo "$crashed_out" | grep -qE "^[[:space:]]*${svc}[[:space:]]*" || echo "$st_out" | grep -qi "crashed"; then
                    [ "$quiet" -eq 0 ] && echo "failed"
                    overall=3
                elif "$RC_SERVICE_BIN" "${rc_user_flag[@]}" "$svc" status &>/dev/null; then
                    [ "$quiet" -eq 0 ] && echo "active"
                else
                    [ "$quiet" -eq 0 ] && echo "inactive"
                    overall=3
                fi
            done
            exit $overall
            ;;

        is-failed)
            if [ ${#units[@]} -eq 0 ]; then
                notice "rc-status --crashed"
                if "$RC_STATUS_BIN" --crashed 2>/dev/null | grep -qE '[a-zA-Z0-9]'; then
                    [ "$quiet" -eq 0 ] && echo "degraded"
                    exit 0
                else
                    [ "$quiet" -eq 0 ] && echo "active"
                    exit 1
                fi
            fi
            local overall=0 u svc st_out crashed_out
            crashed_out=$("$RC_STATUS_BIN" --crashed 2>/dev/null)
            for u in "${units[@]}"; do
                svc=$(normalize_unit "$u")
                notice "rc-service ${rc_user_flag[*]} $svc status"
                st_out=$("$RC_SERVICE_BIN" "${rc_user_flag[@]}" "$svc" status 2>&1 || true)
                if echo "$crashed_out" | grep -qE "^[[:space:]]*${svc}[[:space:]]*" || echo "$st_out" | grep -qi "crashed"; then
                    [ "$quiet" -eq 0 ] && echo "failed"
                else
                    overall=1
                    if echo "$st_out" | grep -qi "started"; then
                        [ "$quiet" -eq 0 ] && echo "active"
                    else
                        [ "$quiet" -eq 0 ] && echo "inactive"
                    fi
                fi
            done
            exit $overall
            ;;

        is-system-running)
            notice "rc-status --crashed"
            if "$RC_STATUS_BIN" --crashed 2>/dev/null | grep -qE '[a-zA-Z0-9]'; then
                [ "$quiet" -eq 0 ] && echo "degraded"
                exit 1
            else
                [ "$quiet" -eq 0 ] && echo "running"
                exit 0
            fi
            ;;

        mask)   for u in "${units[@]}"; do do_mask "$u"; done ;;
        unmask) for u in "${units[@]}"; do do_unmask "$u"; done ;;

        link|revert|add-wants|add-requires)
            el_warning "$action is half-emulated on OpenRC."
            notice "(unit dependency manipulation/linking acknowledged)"
            ;;

        daemon-reload|daemon-reexec|reset-failed|clean|freeze|thaw|set-property|bind|mount-image|service-log-level|service-log-target|log-level|log-target|service-watchdogs)
            notice "(intentional no-op -- OpenRC state/daemon update acknowledged)"
            if [ "$action" = "reset-failed" ] && [ ${#units[@]} -gt 0 ]; then
                check_root
                local u svc
                for u in "${units[@]}"; do
                    svc=$(normalize_unit "$u")
                    "$RC_SERVICE_BIN" "${rc_user_flag[@]}" "$svc" zap 2>/dev/null || true
                done
            fi
            ;;

        whoami)
            notice "id -u"
            id -un 2>/dev/null || echo "root"
            ;;

        list-units|list-automounts|list-paths|list-sockets|list-timers)
            notice "rc-status ${rc_user_flag[*]} --all"
            local raw_status count=0
            raw_status=$("$RC_STATUS_BIN" "${rc_user_flag[@]}" --all 2>/dev/null)
            if [ "$no_legend" -eq 0 ]; then
                printf '  %-36s %-6s %-6s %-10s %s\n' "UNIT" "LOAD" "ACTIVE" "SUB" "DESCRIPTION"
            fi
            local line svc_name status_str load_st active_st sub_st desc init_file match_pat u_pat
            while read -r line; do
                [[ "$line" =~ ^Runlevel: ]] && continue
                [[ "$line" =~ ^[[:space:]]*$ ]] && continue
                svc_name=$(echo "$line" | awk '{print $1}')
                [ -z "$svc_name" ] && continue
                if [ ${#units[@]} -gt 0 ]; then
                    match_pat=0
                    for u_pat in "${units[@]}"; do
                        u_pat=$(normalize_unit "$u_pat")
                        if [[ "$svc_name" == $u_pat ]]; then
                            match_pat=1; break
                        fi
                    done
                    [ "$match_pat" -eq 0 ] && continue
                fi
                if [ -n "$state_filter" ]; then
                    if [ "$state_filter" = "failed" ] && ! echo "$line" | grep -qi "crashed"; then
                        continue
                    fi
                fi
                count=$((count + 1))
                if echo "$line" | grep -qE '\[[[:space:]]*started[[:space:]]*\]'; then
                    active_st="active"
                    sub_st="running"
                else
                    active_st="inactive"
                    sub_st="dead"
                fi
                load_st="loaded"
                desc=""
                init_file="/etc/init.d/$svc_name"
                if [ -r "$init_file" ]; then
                    desc=$(sed -n 's/^[[:space:]]*#[[:space:]]*description:[[:space:]]*\(.*\)/\1/p' "$init_file" 2>/dev/null | head -n 1)
                fi
                [ -z "$desc" ] && desc="$svc_name service"
                printf '  %-36s %-6s %-6s %-10s %s\n' "${svc_name}.service" "$load_st" "$active_st" "$sub_st" "$desc"
            done <<< "$raw_status"
            if [ "$no_legend" -eq 0 ]; then
                echo
                echo "$count loaded units listed."
            fi
            ;;

        list-unit-files)
            notice "rc-update ${rc_user_flag[*]} show -v"
            local show_out count=0 init_f svc_name st_str match_pat u_pat
            show_out=$("$RC_UPDATE_BIN" "${rc_user_flag[@]}" show -v 2>/dev/null)
            if [ "$no_legend" -eq 0 ]; then
                printf '%-40s %-15s %-15s\n' "UNIT FILE" "STATE" "VENDOR PRESET"
            fi
            for init_f in /etc/init.d/*; do
                [ -f "$init_f" ] || continue
                svc_name=$(basename "$init_f")
                if [ ${#units[@]} -gt 0 ]; then
                    match_pat=0
                    for u_pat in "${units[@]}"; do
                        u_pat=$(normalize_unit "$u_pat")
                        if [[ "$svc_name" == $u_pat ]]; then
                            match_pat=1; break
                        fi
                    done
                    [ "$match_pat" -eq 0 ] && continue
                fi
                count=$((count + 1))
                if is_masked "$svc_name"; then
                    st_str="masked"
                elif echo "$show_out" | grep -qE "^[[:space:]]*${svc_name}[[:space:]]*\|[[:space:]]*[A-Za-z]"; then
                    st_str="enabled"
                else
                    st_str="disabled"
                fi
                printf '%-40s %-15s %-15s\n' "${svc_name}.service" "$st_str" "enabled"
            done
            if [ "$no_legend" -eq 0 ]; then
                echo
                echo "$count unit files listed."
            fi
            ;;

        list-machines)
            notice "hostname"
            printf '%-15s %-10s %-10s %-5s %-10s\n' "NAME" "TYPE" "CLASS" "VT" "MACHINE"
            printf '%-15s %-10s %-10s %-5s %-10s\n' ".host" "container" "host" "-" "."
            echo
            echo "1 machines listed."
            ;;

        list-jobs)
            notice "(OpenRC has no job queue)"
            if [ "$quiet" -eq 0 ]; then
                echo "No jobs."
            fi
            ;;

        cancel)
            notice "(no-op: OpenRC has no background systemd jobs to cancel)"
            ;;

        show-environment)
            notice "env"
            env
            ;;

        set-environment)
            check_root
            local env_var
            for env_var in "${units[@]}"; do
                notice "export $env_var"
                export "$env_var" 2>/dev/null || true
                if [ -f /etc/environment ]; then
                    echo "$env_var" >> /etc/environment
                fi
            done
            ;;

        unset-environment)
            check_root
            local env_var
            for env_var in "${units[@]}"; do
                notice "unset $env_var"
                unset "$env_var" 2>/dev/null || true
                if [ -f /etc/environment ]; then
                    sed -i "/^${env_var%=*}=/d" /etc/environment 2>/dev/null || true
                fi
            done
            ;;

        import-environment)
            notice "importing environment variables"
            ;;

        get-default)
            notice "cat /run/openrc/softlevel"
            if   [ -r /run/openrc/softlevel ]; then cat /run/openrc/softlevel
            elif [ -r /var/lib/init.d/softlevel ]; then cat /var/lib/init.d/softlevel
            else echo "default"
            fi
            ;;

        set-default)
            check_root
            local rl; rl=$(map_target_to_runlevel "${units[0]}")
            mkdir -p "$(dirname "$DEFAULT_RUNLEVEL_FILE")"
            notice "echo $rl > $DEFAULT_RUNLEVEL_FILE  (informational; OpenRC uses static runlevels)"
            echo "$rl" > "$DEFAULT_RUNLEVEL_FILE"
            el_warning "set-default is only recorded informationally; OpenRC does not have a single 'default target' concept -- manage runlevels with rc-update."
            ;;

        isolate|default|rescue|emergency)
            check_root
            local rl="default"
            if [ "$action" = "rescue" ] || [ "$action" = "emergency" ]; then
                rl="single"
            elif [ -n "${units[0]}" ]; then
                rl=$(map_target_to_runlevel "${units[0]}")
            fi
            notice "openrc $rl"
            "$OPENRC_BIN" "$rl"
            ;;

        halt|poweroff|reboot|kexec|soft-reboot|exit)
            check_root
            case "$action" in
                halt)
                    notice "halt"
                    exec halt
                    ;;
                poweroff)
                    notice "poweroff"
                    exec poweroff
                    ;;
                reboot|kexec|soft-reboot)
                    notice "reboot"
                    exec reboot
                    ;;
                exit)
                    exit 0
                    ;;
            esac
            ;;

        sleep|suspend|hibernate|hybrid-sleep|suspend-then-hibernate)
            check_root
            notice "sleeping system ($action)"
            if command -v zzz &>/dev/null; then
                exec zzz
            elif command -v pm-suspend &>/dev/null; then
                exec pm-suspend
            elif [ -w /sys/power/state ]; then
                if [ "$action" = "hibernate" ]; then
                    echo disk > /sys/power/state
                else
                    echo mem > /sys/power/state
                fi
            else
                el_error "No supported sleep framework found (zzz, pm-utils, or /sys/power/state writable)."
                exit 1
            fi
            ;;

        switch-root)
            check_root
            el_error "switch-root is not implemented on OpenRC."
            exit 1
            ;;

        edit)
            local svc; svc=$(normalize_unit "${units[0]}")
            notice "\${EDITOR:-vi} /etc/conf.d/$svc"
            "${EDITOR:-vi}" "/etc/conf.d/$svc"
            ;;

        cat)
            local u svc
            for u in "${units[@]}"; do
                svc=$(normalize_unit "$u")
                notice "cat /etc/init.d/$svc /etc/conf.d/$svc"
                echo "# /etc/init.d/$svc"; cat "/etc/init.d/$svc" 2>/dev/null || true
                echo "# /etc/conf.d/$svc"; cat "/etc/conf.d/$svc" 2>/dev/null || true
            done
            ;;

        help)
            if [ ${#units[@]} -gt 0 ]; then
                local u svc
                for u in "${units[@]}"; do
                    svc=$(normalize_unit "$u")
                    if command -v man &>/dev/null && man -w "$svc" &>/dev/null; then
                        notice "man $svc"
                        man "$svc"
                    else
                        notice "rc-service $svc help"
                        "$RC_SERVICE_BIN" "$svc" help 2>/dev/null || echo "No help available for $svc"
                    fi
                done
            else
                cat <<'EOF'
systemctl [OPTIONS...] COMMAND ...

Query or send control commands to the system manager.

Unit Commands:
  list-units [PATTERN...]             List units currently in memory
  list-automounts [PATTERN...]        List automount units currently in memory,
                                      ordered by path
  list-paths [PATTERN...]             List path units currently in memory,
                                      ordered by path
  list-sockets [PATTERN...]           List socket units currently in memory,
                                      ordered by address
  list-timers [PATTERN...]            List timer units currently in memory,
                                      ordered by next elapse
  is-active PATTERN...                Check whether units are active
  is-failed [PATTERN...]              Check whether units are failed or
                                      system is in degraded state
  status [PATTERN...|PID...]          Show runtime status of one or more units
  show [PATTERN...|JOB...]            Show properties of one or more
                                      units/jobs or the manager
  cat PATTERN...                      Show files and drop-ins of specified units
  help PATTERN...|PID...              Show manual for one or more units
  list-dependencies [UNIT...]         Recursively show units which are required
                                      or wanted by the units or by which those
                                      units are required or wanted
  start UNIT...                       Start (activate) one or more units
  stop UNIT...                        Stop (deactivate) one or more units
  reload UNIT...                      Reload one or more units
  restart UNIT...                     Start or restart one or more units
  try-restart UNIT...                 Restart one or more units if active
  reload-or-restart UNIT...           Reload one or more units if possible,
                                      otherwise start or restart
  try-reload-or-restart UNIT...       If active, reload one or more units,
                                      if supported, otherwise restart
  isolate UNIT                        Start one unit and stop all others
  kill UNIT...                        Send signal to processes of a unit
  clean UNIT...                       Clean runtime, cache, state, logs or
                                      configuration of unit
  freeze PATTERN...                   Freeze execution of unit processes
  thaw PATTERN...                     Resume execution of a frozen unit
  set-property UNIT PROPERTY=VALUE... Sets one or more properties of a unit
  bind UNIT PATH [PATH]               Bind-mount a path from the host into a
                                      unit's namespace
  mount-image UNIT PATH [PATH [OPTS]] Mount an image from the host into a
                                      unit's namespace
  service-log-level SERVICE [LEVEL]   Get/set logging threshold for service
  service-log-target SERVICE [TARGET] Get/set logging target for service
  reset-failed [PATTERN...]           Reset failed state for all, one, or more
                                      units
  whoami [PID...]                     Return unit caller or specified PIDs are
                                      part of

Unit File Commands:
  list-unit-files [PATTERN...]        List installed unit files
  enable [UNIT...|PATH...]            Enable one or more unit files
  disable UNIT...                     Disable one or more unit files
  reenable UNIT...                    Reenable one or more unit files
  preset UNIT...                      Enable/disable one or more unit files
                                      based on preset configuration
  preset-all                          Enable/disable all unit files based on
                                      preset configuration
  is-enabled UNIT...                  Check whether unit files are enabled
  mask UNIT...                        Mask one or more units
  unmask UNIT...                      Unmask one or more units
  link PATH...                        Link one or more units files into
                                      the search path
  revert UNIT...                      Revert one or more unit files to vendor
                                      version
  add-wants TARGET UNIT...            Add 'Wants' dependency for the target
                                      on specified one or more units
  add-requires TARGET UNIT...         Add 'Requires' dependency for the target
                                      on specified one or more units
  edit UNIT...                        Edit one or more unit files
  get-default                         Get the name of the default target
  set-default TARGET                  Set the default target

Machine Commands:
  list-machines [PATTERN...]          List local containers and host

Job Commands:
  list-jobs [PATTERN...]              List jobs
  cancel [JOB...]                     Cancel all, one, or more jobs

Environment Commands:
  show-environment                    Dump environment
  set-environment VARIABLE=VALUE...   Set one or more environment variables
  unset-environment VARIABLE...       Unset one or more environment variables
  import-environment VARIABLE...      Import all or some environment variables

Manager State Commands:
  daemon-reload                       Reload systemd manager configuration
  daemon-reexec                       Reexecute systemd manager
  log-level [LEVEL]                   Get/set logging threshold for manager
  log-target [TARGET]                 Get/set logging target for manager
  service-watchdogs [BOOL]            Get/set service watchdog state

System Commands:
  is-system-running                   Check whether system is fully running
  default                             Enter system default mode
  rescue                              Enter system rescue mode
  emergency                           Enter system emergency mode
  halt                                Shut down and halt the system
  poweroff                            Shut down and power-off the system
  reboot                              Shut down and reboot the system
  kexec                               Shut down and reboot the system with kexec
  soft-reboot                         Shut down and reboot userspace
  exit [EXIT_CODE]                    Request user instance or container exit
  switch-root [ROOT [INIT]]           Change to a different root file system
  sleep                               Put the system to sleep (through one of
                                      the operations below)
  suspend                             Suspend the system
  hibernate                           Hibernate the system
  hybrid-sleep                        Hibernate and suspend the system
  suspend-then-hibernate              Suspend the system, wake after a period of
                                      time, and hibernate
Options:
  -h --help              Show this help
     --version           Show package version
     --system            Connect to system manager
     --user              Connect to user service manager
  -C --capsule=NAME      Connect to service manager of specified capsule
  -H --host=[USER@]HOST  Operate on remote host
  -M --machine=CONTAINER Operate on a local container
  -t --type=TYPE         List units of a particular type
     --state=STATE       List units with particular LOAD or SUB or ACTIVE state
     --failed            Shortcut for --state=failed
  -p --property=NAME     Show only properties by this name
  -P NAME                Equivalent to --value --property=NAME
  -a --all               Show all properties/all units currently in memory,
                         including dead/empty ones. To list all units installed
                         on the system, use 'list-unit-files' instead.
  -l --full              Don't ellipsize unit names on output
  -r --recursive         Show unit list of host and local containers
     --reverse           Show reverse dependencies with 'list-dependencies'
     --before            Show units ordered before with 'list-dependencies'
     --after             Show units ordered after with 'list-dependencies'
     --with-dependencies Show unit dependencies with 'status', 'cat',
                         'list-units', and 'list-unit-files'.
     --job-mode=MODE     Specify how to deal with already queued jobs, when
                         queueing a new job
  -T --show-transaction  When enqueuing a unit job, show full transaction
     --show-types        When showing sockets, explicitly show their type
     --value             When showing properties, only print the value
     --check-inhibitors=MODE
                         Whether to check inhibitors before shutting down,
                         sleeping, or hibernating
  -i                     Shortcut for --check-inhibitors=no
     --kill-whom=WHOM    Whom to send signal to
     --kill-value=INT    Signal value to enqueue
  -s --signal=SIGNAL     Which signal to send
     --what=RESOURCES    Which types of resources to remove
     --now               Start or stop unit after enabling or disabling it
     --dry-run           Only print what would be done
                         Currently supported by verbs: halt, poweroff, reboot,
                             kexec, soft-reboot, suspend, hibernate,
                             suspend-then-hibernate, hybrid-sleep, default,
                             rescue, emergency, and exit.
  -q --quiet             Suppress output
     --no-warn           Suppress several warnings shown by default
     --wait              For (re)start, wait until service stopped again
                         For is-system-running, wait until startup is completed
                         For kill, wait until service stopped
     --no-block          Do not wait until operation finished
     --no-wall           Don't send wall message before halt/power-off/reboot
     --message=MESSAGE   Specify human readable reason for system shutdown
     --no-reload         Don't reload daemon after en-/dis-abling unit files
     --legend=BOOL       Enable/disable the legend (column headers and hints)
     --no-pager          Do not pipe output into a pager
     --no-ask-password   Do not ask for system passwords
     --global            Edit/enable/disable/mask default user unit files
                         globally
     --runtime           Edit/enable/disable/mask unit files temporarily until
                         next reboot
  -f --force             When enabling unit files, override existing symlinks
                         When shutting down, execute action immediately
     --preset-mode=      Apply only enable, only disable, or all presets
     --root=PATH         Edit/enable/disable/mask unit files in the specified
                         root directory
     --image=PATH        Edit/enable/disable/mask unit files in the specified
                         disk image
     --image-policy=POLICY
                         Specify disk image dissection policy
  -n --lines=INTEGER     Number of journal entries to show
  -o --output=STRING     Change journal output mode (short, short-precise,
                             short-iso, short-iso-precise, short-full,
                             short-monotonic, short-unix, short-delta,
                             verbose, export, json, json-pretty, json-sse, cat)
     --firmware-setup    Tell the firmware to show the setup menu on next boot
     --boot-loader-menu=TIME
                         Boot into boot loader menu on next boot
     --boot-loader-entry=NAME
                         Boot into a specific boot loader entry on next boot
     --reboot-argument=ARG
                         Specify argument string to pass to reboot()
     --plain             Print unit dependencies as a list instead of a tree
     --timestamp=FORMAT  Change format of printed timestamps (pretty, unix,
                             us, utc, us+utc)
     --read-only         Create read-only bind mount
     --mkdir             Create directory before mounting, if missing
     --marked            Restart/reload previously marked units
     --drop-in=NAME      Edit unit files using the specified drop-in file name
     --when=TIME         Schedule halt/power-off/reboot/kexec action after
                         a certain timestamp
     --stdin             Read new contents of edited file from stdin

See the systemctl(1) man page for details.
EOF
            fi
            ;;

        show)
            if [ ${#units[@]} -eq 0 ]; then
                local arch; arch=$(uname -m 2>/dev/null || echo "x86_64")
                local sys_state="running"
                if "$RC_STATUS_BIN" --crashed 2>/dev/null | grep -qE '[a-zA-Z0-9]'; then
                    sys_state="degraded"
                fi
                local props=(
                    "Version=256 (systemd-openrc-wrapper v$VERSION)"
                    "Features=+OPENRC"
                    "Architecture=$arch"
                    "ActiveState=active"
                    "SystemState=$sys_state"
                    "LogLevel=info"
                    "LogTarget=journal"
                )
                local p
                for p in "${props[@]}"; do
                    if match_property "$p" "${properties[@]}"; then
                        [ "$value_only" -eq 1 ] && echo "${p#*=}" || echo "$p"
                    fi
                done
            else
                local u svc active_st sub_st unit_st load_st desc pid_val init_f
                for u in "${units[@]}"; do
                    svc=$(normalize_unit "$u")
                    init_f="/etc/init.d/$svc"
                    if [ -e "$init_f" ]; then
                        load_st="loaded"
                        desc=$(sed -n 's/^[[:space:]]*#[[:space:]]*description:[[:space:]]*\(.*\)/\1/p' "$init_f" 2>/dev/null | head -n 1)
                    else
                        load_st="not-found"
                        desc=""
                    fi
                    [ -z "$desc" ] && desc="$svc service"

                    notice "rc-service ${rc_user_flag[*]} $svc status"
                    if "$RC_SERVICE_BIN" "${rc_user_flag[@]}" "$svc" status &>/dev/null; then
                        active_st="active"
                        sub_st="running"
                    else
                        active_st="inactive"
                        sub_st="dead"
                    fi
                    unit_st="disabled"
                    if "$RC_UPDATE_BIN" "${rc_user_flag[@]}" show -v 2>/dev/null | grep -qE "^[[:space:]]*${svc}[[:space:]]*\|"; then
                        unit_st="enabled"
                    fi
                    if is_masked "$svc"; then
                        unit_st="masked"
                    fi

                    pid_val="0"
                    if [ "$active_st" = "active" ]; then
                        for pf in "/run/$svc.pid" "/var/run/$svc.pid" "/run/$svc/$svc.pid" "/var/run/$svc/$svc.pid"; do
                            if [ -r "$pf" ]; then
                                pid_val=$(cat "$pf" 2>/dev/null | tr -d ' \n\r')
                                [ -n "$pid_val" ] && break
                            fi
                        done
                        if [ -z "$pid_val" ] || [ "$pid_val" = "0" ]; then
                            pid_val=$(pgrep -o -f "$svc" 2>/dev/null || echo "0")
                        fi
                    fi

                    local props=(
                        "Id=${svc}.service"
                        "Names=${svc}.service"
                        "Description=${desc}"
                        "LoadState=${load_st}"
                        "ActiveState=${active_st}"
                        "SubState=${sub_st}"
                        "UnitFileState=${unit_st}"
                        "MainPID=${pid_val:-0}"
                        "FragmentPath=${init_f}"
                        "CanStart=yes"
                        "CanStop=yes"
                        "CanReload=yes"
                        "NeedDaemonReload=no"
                    )

                    local p
                    for p in "${props[@]}"; do
                        if match_property "$p" "${properties[@]}"; then
                            [ "$value_only" -eq 1 ] && echo "${p#*=}" || echo "$p"
                        fi
                    done
                done
            fi
            ;;

        kill)
            [ "$user_mode" -eq 0 ] && check_root
            local u svc sig="${signal_val:-SIGTERM}" pid_val pf
            for u in "${units[@]}"; do
                svc=$(normalize_unit "$u")
                pid_val=""
                for pf in "/run/$svc.pid" "/var/run/$svc.pid" "/run/$svc/$svc.pid" "/var/run/$svc/$svc.pid"; do
                    if [ -r "$pf" ]; then
                        pid_val=$(cat "$pf" 2>/dev/null | tr -d ' \n\r')
                        [ -n "$pid_val" ] && break
                    fi
                done
                if [ -n "$pid_val" ] && kill -0 "$pid_val" 2>/dev/null; then
                    notice "kill -${sig} $pid_val"
                    kill -"${sig}" "$pid_val" 2>/dev/null || true
                else
                    notice "pkill -${sig} -f $svc"
                    pkill -"${sig}" -f "$svc" 2>/dev/null || true
                fi
            done
            ;;

        list-dependencies)
            el_warning "list-dependencies is only half-emulated on OpenRC -- showing overall service status instead of a real dependency tree."
            notice "rc-status --all"
            "$RC_STATUS_BIN" --all
            ;;

        version)
            echo "systemd 256 (systemd-openrc-wrapper v$VERSION)"
            ;;

        ""|--help)
            cmd_systemctl help
            ;;

        *)
            el_error "systemctl action '$action' is not implemented by this wrapper on OpenRC -- it will not work."
            exit 1
            ;;
    esac
}

# ===========================================================================
# journalctl  (emulated for OpenRC)
# ===========================================================================
cmd_journalctl() {
    local unit="" identifier="" exclude_identifier="" grep_pattern=""
    local follow=0 lines="1000" dmesg=0 reverse=0 quiet=0 no_tail=0
    local action="" field_name="" match_terms=()

    while [ $# -gt 0 ]; do
        case "$1" in
            # Commands
            -h|--help)            action="help"; shift ;;
            --version)            action="version"; shift ;;
            -N|--fields)          action="fields"; shift ;;
            -F|--field)           action="field"; field_name="$2"; shift 2 ;;
            --field=*)            action="field"; field_name="${1#*=}"; shift ;;
            --list-boots)         action="list-boots"; shift ;;
            --list-invocations)   action="list-invocations"; shift ;;
            --list-namespaces)    action="list-namespaces"; shift ;;
            --disk-usage)         action="disk-usage"; shift ;;
            --vacuum-size=*|--vacuum-files=*|--vacuum-time=*)
                                  action="vacuum"; shift ;;
            --vacuum-size|--vacuum-files|--vacuum-time)
                                  action="vacuum"; shift 2 ;;
            --verify)             action="verify"; shift ;;
            --sync)               action="sync"; shift ;;
            --flush)              action="flush"; shift ;;
            --rotate)             action="rotate"; shift ;;
            --relinquish-var|--smart-relinquish-var)
                                  action="relinquish"; shift ;;
            --header)             action="header"; shift ;;
            --list-catalog|--dump-catalog|--update-catalog|--setup-keys)
                                  action="catalog"; shift ;;

            # Filtering & Options
            -u|--unit)            [ $# -ge 2 ] && unit="$2" && shift 2 || shift ;;
            --unit=*)             unit="${1#*=}"; shift ;;
            --user-unit)          [ $# -ge 2 ] && unit="$2" && shift 2 || shift ;;
            --user-unit=*)        unit="${1#*=}"; shift ;;
            -t|--identifier)      [ $# -ge 2 ] && identifier="$2" && shift 2 || shift ;;
            --identifier=*)       identifier="${1#*=}"; shift ;;
            -T|--exclude-identifier) [ $# -ge 2 ] && exclude_identifier="$2" && shift 2 || shift ;;
            --exclude-identifier=*) exclude_identifier="${1#*=}"; shift ;;
            -g|--grep)            [ $# -ge 2 ] && grep_pattern="$2" && shift 2 || shift ;;
            --grep=*)             grep_pattern="${1#*=}"; shift ;;
            -f|--follow)          follow=1; shift ;;
            -n|--lines)
                if [ $# -ge 2 ] && [[ "$2" == "all" || "$2" =~ ^[0-9]+$ ]]; then
                    lines="$2"; shift 2
                else
                    lines="10"; shift
                fi ;;
            --lines=*)            lines="${1#*=}"; shift ;;
            -n*)                  lines="${1#-n}"; shift ;;
            --no-tail)            no_tail=1; shift ;;
            -r|--reverse)         reverse=1; shift ;;
            -k|--dmesg)           dmesg=1; shift ;;
            -q|--quiet)           quiet=1; shift ;;

            # Options with arguments (ignored or best-effort)
            -S|--since|-U|--until|-c|--cursor|--after-cursor|--cursor-file|-b|--boot|--invocation|-p|--priority|--facility|--case-sensitive|-M|--machine|-D|--directory|-i|--file|--root|--image|--image-policy|--namespace|-o|--output|--output-fields|--interval|--verify-key)
                                  shift 2 ;;
            --since=*|--until=*|--cursor=*|--after-cursor=*|--cursor-file=*|--boot=*|--invocation=*|--priority=*|--facility=*|--case-sensitive=*|--machine=*|--directory=*|--file=*|--root=*|--image=*|--image-policy=*|--namespace=*|--output=*|--output-fields=*|--interval=*|--verify-key=*)
                                  shift ;;

            # Boolean switches (ignored)
            -I|-x|-e|-a|--all|--no-pager|--show-cursor|--utc|--no-hostname|--no-full|--catalog|--truncate-newline|--force|--system|--user|-m)
                                  shift ;;

            --)                   shift; match_terms+=("$@"); break ;;
            -*)                   shift ;;
            *)
                if [[ "$1" == _SYSTEMD_UNIT=* || "$1" == UNIT=* ]]; then
                    unit="${1#*=}"
                elif [[ "$1" == SYSLOG_IDENTIFIER=* ]]; then
                    identifier="${1#*=}"
                else
                    match_terms+=("$1")
                fi
                shift
                ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
journalctl [OPTIONS...] [MATCHES...]

Query the OpenRC system log (emulated journalctl).

Source Options:
     --system                Show system log
     --user                  Show user log
  -M --machine=CONTAINER     Operate on local container (ignored)
  -m --merge                 Show entries from available logs
  -D --directory=PATH        Specify log directory
  -i --file=PATH             Specify log file

Filtering Options:
  -S --since=DATE            Show entries not older than DATE (ignored)
  -U --until=DATE            Show entries not newer than DATE (ignored)
  -b --boot[=ID]             Show current boot log
  -u --unit=UNIT             Show logs from specified unit
     --user-unit=UNIT        Show logs from specified user unit
  -t --identifier=STRING     Show entries with specified syslog identifier
  -T --exclude-identifier=STR Hide entries with specified syslog identifier
  -p --priority=RANGE        Show entries within priority range (ignored)
  -g --grep=PATTERN          Show entries with MESSAGE matching PATTERN
  -k --dmesg                 Show kernel message log (dmesg)

Output Control Options:
  -o --output=STRING         Change output mode (ignored)
  -n --lines=INTEGER         Number of journal entries to show
  -r --reverse               Show newest entries first
  -a --all                   Show all fields
  -f --follow                Follow log stream
     --no-tail               Show all lines, even in follow mode
  -q --quiet                 Suppress info messages

Commands:
  -h --help                  Show this help text
     --version               Show package version
  -N --fields                List field names
  -F --field=FIELD           List field values
     --list-boots            Show recorded boot information
     --list-namespaces       Show list of namespaces
     --disk-usage            Show total disk usage of log files
     --vacuum-size=BYTES     Reduce disk usage (runs logrotate)
     --vacuum-files=INT      Reduce disk usage (runs logrotate)
     --vacuum-time=TIME      Reduce disk usage (runs logrotate)
     --verify                Verify log file consistency
     --sync                  Synchronize unwritten log messages
     --flush                 Flush journal data
     --rotate                Rotate log files
     --header                Show log header information
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (journalctl OpenRC wrapper v$VERSION)"
            return 0
            ;;
        list-boots)
            notice "journalctl --list-boots"
            local boot_id; boot_id=$(cat /proc/sys/kernel/random/boot_id 2>/dev/null || echo "00000000000000000000000000000000")
            local boot_time; boot_time=$(uptime -s 2>/dev/null || date)
            echo " 0 ${boot_id//-/} $boot_time — $(date)"
            return 0
            ;;
        list-namespaces)
            echo "default"
            return 0
            ;;
        fields)
            echo "_SYSTEMD_UNIT"
            echo "SYSLOG_IDENTIFIER"
            echo "MESSAGE"
            echo "PRIORITY"
            echo "_PID"
            echo "_HOSTNAME"
            echo "_COMM"
            echo "_BOOT_ID"
            echo "_TRANSPORT"
            return 0
            ;;
        field)
            if [ "$field_name" = "_SYSTEMD_UNIT" ] || [ "$field_name" = "UNIT" ]; then
                "$RC_STATUS_BIN" --all 2>/dev/null | awk '{print $1}' | grep -v '^Runlevel:' | sort -u
            elif [ "$field_name" = "SYSLOG_IDENTIFIER" ]; then
                ls /var/log 2>/dev/null
            else
                echo "MESSAGE"
            fi
            return 0
            ;;
        disk-usage)
            local usage; usage=$(du -sh /var/log 2>/dev/null | awk '{print $1}')
            echo "Archived and active journals take up ${usage:-0B} on disk."
            return 0
            ;;
        vacuum)
            notice "(OpenRC log maintenance)"
            [ "$quiet" -eq 0 ] && el_info "Log retention on OpenRC is managed by logrotate/syslog."
            if command -v logrotate &>/dev/null && [ -f /etc/logrotate.conf ]; then
                logrotate /etc/logrotate.conf 2>/dev/null || true
            fi
            echo "Vacuuming complete."
            return 0
            ;;
        verify)
            echo "PASS: /var/log files verified."
            return 0
            ;;
        sync|flush|rotate)
            sync
            if command -v logrotate &>/dev/null && [ -f /etc/logrotate.conf ]; then
                logrotate /etc/logrotate.conf 2>/dev/null || true
            fi
            echo "Journal action $action completed."
            return 0
            ;;
        relinquish|header|catalog)
            notice "(no-op $action on OpenRC)"
            [ "$action" = "header" ] && echo "File: /var/log/syslog (OpenRC syslog emulation)"
            return 0
            ;;
    esac

    if [ "$lines" = "all" ]; then
        no_tail=1
        lines="100000"
    fi

    if [ "$dmesg" -eq 1 ]; then
        notice "dmesg"
        exec dmesg
    fi

    local logfile="" svc="" alt_svc1="" alt_svc2=""
    if [ -n "$unit" ]; then
        svc=$(normalize_unit "$unit")
        alt_svc1="${svc}d"
        alt_svc2="${svc%d}"
        for f in "/var/log/$svc/current" "/var/log/$svc.log" "/var/log/$svc/$svc.log" "/var/log/$svc" "/var/log/$alt_svc1.log" "/var/log/$alt_svc2.log"; do
            [ -f "$f" ] && { logfile="$f"; break; }
        done
    fi
    if [ -z "$logfile" ] && [ -n "$identifier" ]; then
        for f in "/var/log/$identifier/current" "/var/log/$identifier.log" "/var/log/$identifier/$identifier.log"; do
            [ -f "$f" ] && { logfile="$f"; break; }
        done
    fi
    if [ -z "$logfile" ]; then
        for f in /var/log/syslog /var/log/messages /var/log/daemon.log /var/log/user.log /var/log/auth.log /var/log/everything/current /var/log/rc.log; do
            [ -f "$f" ] && { logfile="$f"; break; }
        done
    fi

    if [ -z "$logfile" ]; then
        if command -v logread &>/dev/null; then
            [ "$quiet" -eq 0 ] && el_warning "No systemd journal exists on OpenRC -- falling back to logread."
            notice "logread$( [ "$follow" -eq 1 ] && echo " -f")"
            if [ "$follow" -eq 1 ]; then
                exec logread -f
            else
                exec logread
            fi
        fi
        el_error "No suitable log source found (no syslog file, no logread) -- journalctl cannot be emulated here."
        exit 1
    fi

    [ "$quiet" -eq 0 ] && el_warning "There is no real journal on OpenRC -- output is a best-effort grep/tail over $logfile."

    filter_logs() {
        {
            if [ -n "$svc" ] && [ "$logfile" != "/var/log/$svc" ] && [ "$logfile" != "/var/log/$svc.log" ] && [ "$logfile" != "/var/log/$svc/current" ]; then
                grep -i -E "($svc|${svc}d|${svc%d})"
            else
                cat
            fi
        } | {
            if [ -n "$identifier" ]; then grep -i "$identifier"; else cat; fi
        } | {
            if [ -n "$exclude_identifier" ]; then grep -v -i "$exclude_identifier"; else cat; fi
        } | {
            if [ -n "$grep_pattern" ]; then grep -E "$grep_pattern"; else cat; fi
        } | {
            if [ ${#match_terms[@]} -gt 0 ]; then
                local term
                for term in "${match_terms[@]}"; do
                    grep -i "$term"
                done
            else
                cat
            fi
        } | {
            if [ "$output_val" = "cat" ]; then
                sed -E 's/^[A-Za-z]{3} +[0-9]+ [0-9:]+ [^ ]+ [^:]+: //'
            elif [[ "$output_val" == json* ]]; then
                awk '{
                    msg = $0;
                    gsub(/"/, "\\\"", msg);
                    print "{\"__REALTIME_TIMESTAMP\":\"" systime() "000000\",\"MESSAGE\":\"" msg "\"}"
                }'
            else
                cat
            fi
        }
    }

    if [ "$follow" -eq 1 ]; then
        notice "tail -F -n ${lines:-100} $logfile | filter"
        tail -F -n "${lines:-100}" "$logfile" | filter_logs
    else
        notice "filter $logfile | tail -n ${lines:-1000}"
        if [ "$reverse" -eq 1 ]; then
            if [ "$no_tail" -eq 1 ]; then
                filter_logs < "$logfile" | { if command -v tac &>/dev/null; then tac; else awk '{a[NR]=$0} END {for(i=NR;i>0;i--) print a[i]}'; fi; }
            else
                filter_logs < "$logfile" | tail -n "${lines:-1000}" | { if command -v tac &>/dev/null; then tac; else awk '{a[NR]=$0} END {for(i=NR;i>0;i--) print a[i]}'; fi; }
            fi
        else
            if [ "$no_tail" -eq 1 ]; then
                filter_logs < "$logfile"
            else
                filter_logs < "$logfile" | tail -n "${lines:-1000}"
            fi
        fi
    fi
}

# ===========================================================================
# hostnamectl
# ===========================================================================
cmd_hostnamectl() {
    local json_mode="" host_val="" machine_val="" parsed_action=""
    local transient_flag=0 static_flag=0 pretty_flag=0
    local rest=()

    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help|help)        parsed_action="help"; shift ;;
            --version|version)     parsed_action="version"; shift ;;
            --no-ask-password)     shift ;;
            -H|--host)             host_val="$2"; shift 2 ;;
            --host=*)              host_val="${1#*=}"; shift ;;
            -M|--machine)          machine_val="$2"; shift 2 ;;
            --machine=*)           machine_val="${1#*=}"; shift ;;
            --transient)           transient_flag=1; shift ;;
            --static)              static_flag=1; shift ;;
            --pretty)              pretty_flag=1; shift ;;
            --json=*)              json_mode="${1#*=}"; shift ;;
            --json)                json_mode="pretty"; shift ;;
            -j)                    json_mode="pretty"; shift ;;
            --)                    shift; rest+=("$@"); break ;;
            -*)                    shift ;;
            *)                     rest+=("$1"); shift ;;
        esac
    done
    set -- "${rest[@]}"

    local action="${parsed_action:-$1}"
    if [ -z "$parsed_action" ]; then shift 2>/dev/null || true; fi
    local target_args=("$@")

    get_mi() {
        local key="$1"
        if [ -f /etc/machine-info ]; then
            (grep "^${key}=" /etc/machine-info 2>/dev/null || true) | cut -d= -f2- | sed -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'$//"
        fi
        return 0
    }

    detect_chassis() {
        local c; c=$(get_mi CHASSIS)
        if [ -n "$c" ]; then
            echo "$c"
            return 0
        fi
        if cmd_systemd_detect_virt --container &>/dev/null; then
            echo "container"
            return 0
        fi
        if cmd_systemd_detect_virt --vm &>/dev/null; then
            echo "vm"
            return 0
        fi
        if [ -r /sys/class/dmi/id/chassis_type ]; then
            local raw_type; raw_type=$(cat /sys/class/dmi/id/chassis_type 2>/dev/null)
            case "$raw_type" in
                8|9|10|12|14) echo "laptop" ; return 0 ;;
                3|4|5|6|7|13|15|16|24) echo "desktop" ; return 0 ;;
                17|23|28|29) echo "server" ; return 0 ;;
                11|30) echo "tablet" ; return 0 ;;
                31|32) echo "convertible" ; return 0 ;;
            esac
        fi
        if [ -d /sys/class/power_supply ]; then
            if grep -qi "Battery" /sys/class/power_supply/*/type 2>/dev/null; then
                echo "laptop"
                return 0
            fi
        fi
        echo "desktop"
    }

    detect_icon_name() {
        local icon; icon=$(get_mi ICON_NAME)
        if [ -n "$icon" ]; then
            echo "$icon"
            return 0
        fi
        local chassis; chassis=$(detect_chassis)
        case "$chassis" in
            laptop)      echo "computer-laptop" ;;
            desktop)     echo "computer-desktop" ;;
            server)      echo "computer-server" ;;
            tablet)      echo "computer-tablet" ;;
            container)   echo "container" ;;
            vm)          echo "computer-vm" ;;
            *)           echo "computer" ;;
        esac
    }

    set_mi() {
        local key="$1" val="$2"
        check_root
        touch /etc/machine-info
        if [ -z "$val" ]; then
            sed -i "/^${key}=/d" /etc/machine-info
        elif grep -q "^${key}=" /etc/machine-info 2>/dev/null; then
            sed -i "s|^${key}=.*|${key}=\"${val}\"|" /etc/machine-info
        else
            echo "${key}=\"${val}\"" >> /etc/machine-info
        fi
    }

    case "$action" in
        ""|status)
            notice "cat /etc/hostname"
            local static_h; static_h=$(cat /etc/hostname 2>/dev/null || hostname)
            local pretty_h; pretty_h=$(get_mi PRETTY_HOSTNAME)
            local icon_n; icon_n=$(detect_icon_name)
            local chassis_v; chassis_v=$(detect_chassis)
            local deploy_v; deploy_v=$(get_mi DEPLOYMENT)
            local loc_v; loc_v=$(get_mi LOCATION)
            local mach_id; mach_id=$(cat /etc/machine-id 2>/dev/null | tr -d '\n\r')
            local boot_id; boot_id=$(cat /proc/sys/kernel/random/boot_id 2>/dev/null | tr -d '\n\r')
            local os_v; os_v=$(. /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")
            local kernel_v; kernel_v=$(uname -sr)
            local arch_v; arch_v=$(uname -m)

            if [ -n "$json_mode" ] && [ "$json_mode" != "off" ]; then
                printf '{"Hostname":"%s","StaticHostname":"%s","PrettyHostname":%s,"IconName":%s,"Chassis":%s,"Deployment":%s,"Location":%s,"OperatingSystem":"%s","Kernel":"%s","Architecture":"%s"}\n' \
                    "$(hostname)" "$static_h" \
                    "${pretty_h:+\"$pretty_h\"}${pretty_h:-null}" \
                    "${icon_n:+\"$icon_n\"}${icon_n:-null}" \
                    "${chassis_v:+\"$chassis_v\"}${chassis_v:-null}" \
                    "${deploy_v:+\"$deploy_v\"}${deploy_v:-null}" \
                    "${loc_v:+\"$loc_v\"}${loc_v:-null}" \
                    "$os_v" "$kernel_v" "$arch_v"
                return 0
            fi

            echo " Static hostname: $static_h"
            [ -n "$pretty_h" ]   && echo " Pretty hostname: $pretty_h"
            [ -n "$icon_n" ]     && echo "      Icon name: $icon_n"
            [ -n "$chassis_v" ]  && echo "        Chassis: $chassis_v"
            [ -n "$deploy_v" ]   && echo "     Deployment: $deploy_v"
            [ -n "$loc_v" ]      && echo "       Location: $loc_v"
            [ -n "$mach_id" ]    && echo "     Machine ID: $mach_id"
            [ -n "$boot_id" ]    && echo "        Boot ID: $boot_id"
            echo "Operating System: $os_v"
            echo "          Kernel: $kernel_v"
            echo "    Architecture: $arch_v"
            ;;

        hostname)
            local new_name="${target_args[0]}"
            if [ -n "$new_name" ]; then
                if [ "$pretty_flag" -eq 1 ]; then
                    set_mi PRETTY_HOSTNAME "$new_name"
                fi
                if [ "$static_flag" -eq 1 ] || [ "$pretty_flag" -eq 0 ]; then
                    check_root
                    notice "echo $new_name > /etc/hostname && rc-service hostname restart"
                    local old_name
                    old_name=$(cat /etc/hostname 2>/dev/null || hostname)
                    echo "$new_name" > /etc/hostname
                    [ -f /etc/conf.d/hostname ] && sed -i "s/^hostname=.*/hostname=\"$new_name\"/" /etc/conf.d/hostname
                    if [ -f /etc/hosts ] && [ -n "$old_name" ]; then
                        sed -i "s/\b${old_name}\b/${new_name}/g" /etc/hosts 2>/dev/null || true
                    fi
                    hostname "$new_name" 2>/dev/null
                    "$RC_SERVICE_BIN" hostname restart &>/dev/null || true
                    el_notify normal "preferences-system" "Hostname changed" "New hostname: $new_name" 2>/dev/null
                fi
            else
                if [ "$pretty_flag" -eq 1 ]; then
                    get_mi PRETTY_HOSTNAME || hostname
                elif [ "$static_flag" -eq 1 ]; then
                    cat /etc/hostname 2>/dev/null || hostname
                elif [ "$transient_flag" -eq 1 ]; then
                    hostname
                else
                    cat /etc/hostname 2>/dev/null || hostname
                fi
            fi
            ;;

        set-hostname)
            local name="${target_args[0]}"
            [ -z "$name" ] && die "set-hostname requires a name"
            if [ "$pretty_flag" -eq 1 ]; then
                set_mi PRETTY_HOSTNAME "$name"
            elif [ "$static_flag" -eq 1 ]; then
                check_root
                notice "echo $name > /etc/hostname && rc-service hostname restart"
                local old_name
                old_name=$(cat /etc/hostname 2>/dev/null || hostname)
                echo "$name" > /etc/hostname
                [ -f /etc/conf.d/hostname ] && sed -i "s/^hostname=.*/hostname=\"$name\"/" /etc/conf.d/hostname
                if [ -f /etc/hosts ] && [ -n "$old_name" ]; then
                    sed -i "s/\b${old_name}\b/${name}/g" /etc/hosts 2>/dev/null || true
                fi
                hostname "$name" 2>/dev/null
                "$RC_SERVICE_BIN" hostname restart &>/dev/null || true
                el_notify normal "preferences-system" "Hostname changed" "New hostname: $name" 2>/dev/null
            else
                check_root
                local static_name
                static_name=$(echo "$name" | tr '[:upper:]' '[:lower:]' | tr ' ' '-' | tr -cd 'a-z0-9.-')
                if [ "$static_name" != "$name" ]; then
                    set_mi PRETTY_HOSTNAME "$name"
                fi
                notice "echo ${static_name:-$name} > /etc/hostname && rc-service hostname restart"
                local old_name
                old_name=$(cat /etc/hostname 2>/dev/null || hostname)
                echo "${static_name:-$name}" > /etc/hostname
                [ -f /etc/conf.d/hostname ] && sed -i "s/^hostname=.*/hostname=\"${static_name:-$name}\"/" /etc/conf.d/hostname
                if [ -f /etc/hosts ] && [ -n "$old_name" ]; then
                    sed -i "s/\b${old_name}\b/${static_name:-$name}/g" /etc/hosts 2>/dev/null || true
                fi
                hostname "${static_name:-$name}" 2>/dev/null
                "$RC_SERVICE_BIN" hostname restart &>/dev/null || true
                el_notify normal "preferences-system" "Hostname changed" "New hostname: ${static_name:-$name}" 2>/dev/null
            fi
            ;;

        icon-name|set-icon-name)
            local val="${target_args[0]}"
            if [ -n "$val" ] || [ "$action" = "set-icon-name" ]; then
                set_mi ICON_NAME "$val"
            else
                detect_icon_name
            fi
            ;;

        chassis|set-chassis)
            local val="${target_args[0]}"
            if [ -n "$val" ] || [ "$action" = "set-chassis" ]; then
                set_mi CHASSIS "$val"
            else
                detect_chassis
            fi
            ;;

        deployment|set-deployment)
            local val="${target_args[0]}"
            if [ -n "$val" ] || [ "$action" = "set-deployment" ]; then
                set_mi DEPLOYMENT "$val"
            else
                get_mi DEPLOYMENT
            fi
            ;;

        location|set-location)
            local val="${target_args[0]}"
            if [ -n "$val" ] || [ "$action" = "set-location" ]; then
                set_mi LOCATION "$val"
            else
                get_mi LOCATION
            fi
            ;;

        help)
            cat <<'EOF'
hostnamectl [OPTIONS...] COMMAND ...

Query or change system hostname.

Commands:
  status                 Show current hostname settings
  hostname [NAME]        Get/set system hostname
  icon-name [NAME]       Get/set icon name for host
  chassis [NAME]         Get/set chassis type for host
  deployment [NAME]      Get/set deployment environment for host
  location [NAME]        Get/set location for host

Options:
  -h --help              Show this help
     --version           Show package version
     --no-ask-password   Do not prompt for password
  -H --host=[USER@]HOST  Operate on remote host
  -M --machine=CONTAINER Operate on local container
     --transient         Only set transient hostname
     --static            Only set static hostname
     --pretty            Only set pretty hostname
     --json=pretty|short|off
                         Generate JSON output
  -j                     Same as --json=pretty on tty, --json=short otherwise

See the hostnamectl(1) man page for details.
EOF
            ;;

        version)
            echo "systemd $VERSION (hostnamectl OpenRC wrapper)"
            ;;

        *)
            el_error "hostnamectl action '$action' is not implemented."
            exit 1
            ;;
    esac
}

# ===========================================================================
# timedatectl
# ===========================================================================
cmd_timedatectl() {
    require_openrc

    local properties=() value_only=0 all_flag=0 host_val="" machine_val="" json_mode=""
    local adjust_system_clock=0 monitor_flag=0 parsed_action=""
    local rest=()

    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help|help)        parsed_action="help"; shift ;;
            --version|version)     parsed_action="version"; shift ;;
            --no-pager|--no-ask-password) shift ;;
            -H|--host)             host_val="$2"; shift 2 ;;
            --host=*)              host_val="${1#*=}"; shift ;;
            -M|--machine)          machine_val="$2"; shift 2 ;;
            --machine=*)           machine_val="${1#*=}"; shift ;;
            --adjust-system-clock) adjust_system_clock=1; shift ;;
            --monitor)             monitor_flag=1; shift ;;
            -p|--property)         properties+=("$2"); shift 2 ;;
            --property=*)          properties+=("${1#*=}"); shift ;;
            -p*)                   properties+=("${1#-p}"); shift ;;
            -P)                    value_only=1; properties+=("$2"); shift 2 ;;
            -P*)                   value_only=1; properties+=("${1#-P}"); shift ;;
            --value)               value_only=1; shift ;;
            -a|--all)              all_flag=1; shift ;;
            --json=*)              json_mode="${1#*=}"; shift ;;
            --json)                json_mode="pretty"; shift ;;
            -j)                    json_mode="pretty"; shift ;;
            --)                    shift; rest+=("$@"); break ;;
            -*)                    shift ;;
            *)                     rest+=("$1"); shift ;;
        esac
    done
    set -- "${rest[@]}"

    local action="${parsed_action:-$1}"
    if [ -z "$parsed_action" ]; then shift 2>/dev/null || true; fi
    local target_args=("$@")

    local tz
    tz=$(cat /etc/timezone 2>/dev/null)
    if [ -z "$tz" ] && [ -L /etc/localtime ]; then
        tz=$(readlink -f /etc/localtime 2>/dev/null | sed 's#.*/zoneinfo/##')
    fi
    [ -z "$tz" ] && tz="UTC"

    local is_local_rtc="no"
    if [ -f /etc/conf.d/hwclock ] && grep -qi 'clock="local"' /etc/conf.d/hwclock; then
        is_local_rtc="yes"
    elif [ -f /etc/adjtime ] && grep -qi '^LOCAL' /etc/adjtime; then
        is_local_rtc="yes"
    fi

    local ntp_svc="" ntp_active="inactive" ntp_sync="no"
    local candidate
    for candidate in chronyd chrony ntpd ntp openntpd systemd-timesyncd; do
        if "$RC_SERVICE_BIN" "$candidate" status &>/dev/null; then
            ntp_svc="$candidate"
            ntp_active="active"
            ntp_sync="yes"
            break
        elif [ -z "$ntp_svc" ] && "$RC_UPDATE_BIN" show default 2>/dev/null | grep -q "$candidate"; then
            ntp_svc="$candidate"
        fi
    done

    case "$action" in
        ""|status)
            notice "date; cat /etc/timezone"
            local local_time utc_time rtc_time tz_abbr tz_off
            local_time=$(date "+%a %Y-%m-%d %H:%M:%S %Z")
            utc_time=$(date -u "+%a %Y-%m-%d %H:%M:%S UTC")
            tz_abbr=$(date "+%Z")
            tz_off=$(date "+%z")

            if command -v hwclock &>/dev/null; then
                rtc_time=$(hwclock --show 2>/dev/null | head -n 1)
            fi
            [ -z "$rtc_time" ] && rtc_time="n/a"

            if [ -n "$json_mode" ] && [ "$json_mode" != "off" ]; then
                printf '{"Timezone":"%s","LocalRTC":%s,"CanNTP":true,"NTP":%s,"NTPSynchronized":%s}\n' \
                    "$tz" "$([ "$is_local_rtc" = "yes" ] && echo true || echo false)" \
                    "$([ "$ntp_active" = "active" ] && echo true || echo false)" \
                    "$([ "$ntp_sync" = "yes" ] && echo true || echo false)"
                return 0
            fi

            echo "               Local time: $local_time"
            echo "           Universal time: $utc_time"
            echo "                 RTC time: $rtc_time"
            echo "                Time zone: $tz ($tz_abbr, $tz_off)"
            echo "System clock synchronized: $ntp_sync"
            echo "              NTP service: $ntp_active"
            echo "          RTC in local TZ: $is_local_rtc"
            ;;

        show)
            local time_usec
            time_usec=$(($(date +%s) * 1000000))
            local props=(
                "Timezone=$tz"
                "LocalRTC=$is_local_rtc"
                "CanNTP=yes"
                "NTP=$([ "$ntp_active" = "active" ] && echo "yes" || echo "no")"
                "NTPSynchronized=$ntp_sync"
                "TimeUSec=$time_usec"
                "RTCTimeUSec="
            )

            local p
            for p in "${props[@]}"; do
                if match_property "$p" "${properties[@]}"; then
                    [ "$value_only" -eq 1 ] && echo "${p#*=}" || echo "$p"
                fi
            done
            ;;

        set-time)
            local new_time="${target_args[0]}"
            [ -z "$new_time" ] && die "set-time requires a time string"
            check_root
            notice "date -s '$new_time' && hwclock --systohc"
            date -s "$new_time" && command -v hwclock &>/dev/null && hwclock --systohc 2>/dev/null || true
            ;;

        set-timezone)
            local new_tz="${target_args[0]}"
            [ -z "$new_tz" ] && die "set-timezone requires a timezone"
            [ -e "/usr/share/zoneinfo/$new_tz" ] || die "unknown timezone: $new_tz"
            check_root
            notice "ln -sf /usr/share/zoneinfo/$new_tz /etc/localtime && echo $new_tz > /etc/timezone"
            ln -sf "/usr/share/zoneinfo/$new_tz" /etc/localtime
            echo "$new_tz" > /etc/timezone
            ;;

        list-timezones)
            find /usr/share/zoneinfo -type f 2>/dev/null | sed 's#/usr/share/zoneinfo/##' | grep -v '\.tab$' | grep -v 'posix/' | grep -v 'right/' | sort -u
            ;;

        set-local-rtc)
            local val="${target_args[0]}"
            [ -z "$val" ] && die "set-local-rtc requires a boolean value (1/0, yes/no, true/false)"
            check_root
            local rtc_mode="UTC"
            case "$val" in
                1|true|yes|on)  rtc_mode="local" ;;
                0|false|no|off) rtc_mode="UTC" ;;
                *) die "invalid boolean value: $val" ;;
            esac

            notice "setting RTC mode to $rtc_mode in /etc/conf.d/hwclock or /etc/adjtime"
            if [ -f /etc/conf.d/hwclock ]; then
                sed -i "s/^clock=.*/clock=\"$rtc_mode\"/" /etc/conf.d/hwclock
            elif [ -f /etc/adjtime ]; then
                if [ "$rtc_mode" = "local" ]; then
                    sed -i 's/^UTC/LOCAL/' /etc/adjtime 2>/dev/null || echo "LOCAL" >> /etc/adjtime
                else
                    sed -i 's/^LOCAL/UTC/' /etc/adjtime 2>/dev/null || echo "UTC" >> /etc/adjtime
                fi
            else
                mkdir -p /etc/conf.d
                echo "clock=\"$rtc_mode\"" > /etc/conf.d/hwclock
            fi

            if [ "$adjust_system_clock" -eq 1 ] && command -v hwclock &>/dev/null; then
                if [ "$rtc_mode" = "local" ]; then
                    hwclock --hctosys --localtime 2>/dev/null || true
                else
                    hwclock --hctosys --utc 2>/dev/null || true
                fi
            fi
            ;;

        set-ntp)
            local val="${target_args[0]}"
            [ -z "$val" ] && die "set-ntp requires a boolean value (1/0, yes/no, true/false)"
            check_root
            local enable_ntp=0
            case "$val" in
                1|true|yes|on)  enable_ntp=1 ;;
                0|false|no|off) enable_ntp=0 ;;
                *) die "invalid boolean value: $val" ;;
            esac

            local target_daemon=""
            for candidate in chronyd chrony ntpd ntp ntpsec openntpd systemd-timesyncd; do
                if command -v "$candidate" &>/dev/null || [ -f "/etc/init.d/$candidate" ]; then
                    target_daemon="$candidate"
                    break
                fi
            done

            if [ -z "$target_daemon" ]; then
                el_error "No supported NTP daemon (chronyd, ntpd, openntpd) found."
                exit 1
            fi

            if [ "$enable_ntp" -eq 1 ]; then
                notice "rc-update add $target_daemon default && rc-service $target_daemon start"
                "$RC_UPDATE_BIN" add "$target_daemon" default 2>/dev/null || true
                "$RC_SERVICE_BIN" "$target_daemon" start
            else
                notice "rc-service $target_daemon stop && rc-update del $target_daemon default"
                "$RC_SERVICE_BIN" "$target_daemon" stop 2>/dev/null || true
                "$RC_UPDATE_BIN" del "$target_daemon" default 2>/dev/null || true
            fi
            ;;

        timesync-status)
            notice "timesync status"
            if command -v chronyc &>/dev/null; then
                chronyc tracking 2>/dev/null || chronyc sources 2>/dev/null
            elif command -v ntpq &>/dev/null; then
                ntpq -p 2>/dev/null
            else
                echo "       Server: n/a (emulated NTP status)"
                echo "Poll interval: n/a"
                echo "         Leap: normal"
                echo "       Offset: 0.000000 s"
                echo "        Delay: 0.000000 s"
                echo "       Jitter: 0.000000 s"
            fi
            ;;

        show-timesync)
            local props=(
                "ServerName="
                "ServerAddress="
                "RootDistanceMaxUSec=5000000"
                "PollIntervalMinUSec=32000000"
                "PollIntervalMaxUSec=2048000000"
                "PollIntervalUSec=128000000"
                "NTPMessage="
                "JitterUSec=0"
            )
            local p
            for p in "${props[@]}"; do
                if [ -n "$property" ]; then
                    if [[ "$p" == "${property}="* ]]; then
                        [ "$value_only" -eq 1 ] && echo "${p#*=}" || echo "$p"
                    fi
                else
                    [ "$value_only" -eq 1 ] && echo "${p#*=}" || echo "$p"
                fi
            done
            ;;

        ntp-servers|revert)
            notice "ntp-servers / revert acknowledged for ${target_args[*]}"
            el_warning "$action is informational on OpenRC (interface-specific NTP servers require systemd-resolved/timesyncd)."
            ;;

        help)
            cat <<'EOF'
timedatectl [OPTIONS...] COMMAND ...

Query or change system time and date settings.

Commands:
  status                   Show current time settings
  show                     Show properties of systemd-timedated
  set-time TIME            Set system time
  set-timezone ZONE        Set system time zone
  list-timezones           Show known time zones
  set-local-rtc BOOL       Control whether RTC is in local time
  set-ntp BOOL             Enable or disable network time synchronization

systemd-timesyncd Commands:
  timesync-status          Show status of systemd-timesyncd
  show-timesync            Show properties of systemd-timesyncd
  ntp-servers INTERFACE SERVER…
                           Set the interface specific NTP servers
  revert INTERFACE         Revert the interface specific NTP servers

Options:
  -h --help                Show this help message
     --version             Show package version
     --no-pager            Do not pipe output into a pager
     --no-ask-password     Do not prompt for password
  -H --host=[USER@]HOST    Operate on remote host
  -M --machine=CONTAINER   Operate on local container
     --adjust-system-clock Adjust system clock when changing local RTC mode
     --monitor             Monitor status of systemd-timesyncd
  -p --property=NAME       Show only properties by this name
  -a --all                 Show all properties, including empty ones
     --value               When showing properties, only print the value
  -P NAME                  Equivalent to --value --property=NAME

See the timedatectl(1) man page for details.
EOF
            ;;

        version)
            echo "systemd $VERSION (timedatectl OpenRC wrapper)"
            ;;

        *)
            el_error "timedatectl action '$action' is not implemented."
            exit 1
            ;;
    esac
}

# ===========================================================================
# localectl
# ===========================================================================
cmd_localectl() {
    require_openrc

    local properties=() value_only=0 all_flag=0 host_val="" machine_val=""
    local no_convert=0 json_mode="" parsed_action=""
    local rest=()

    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help|help)        parsed_action="help"; shift ;;
            --version|version)     parsed_action="version"; shift ;;
            --no-pager|--no-ask-password|--full|-l) shift ;;
            --no-convert)          no_convert=1; shift ;;
            -p|--property)         properties+=("$2"); shift 2 ;;
            --property=*)          properties+=("${1#*=}"); shift ;;
            -p*)                   properties+=("${1#-p}"); shift ;;
            -P)                    value_only=1; properties+=("$2"); shift 2 ;;
            -P*)                   value_only=1; properties+=("${1#-P}"); shift ;;
            --value)               value_only=1; shift ;;
            -a|--all)              all_flag=1; shift ;;
            -H|--host)             host_val="$2"; shift 2 ;;
            --host=*)              host_val="${1#*=}"; shift ;;
            -M|--machine)          machine_val="$2"; shift 2 ;;
            --machine=*)           machine_val="${1#*=}"; shift ;;
            --json=*)              json_mode="${1#*=}"; shift ;;
            --json)                json_mode="pretty"; shift ;;
            -j)                    json_mode="pretty"; shift ;;
            --)                    shift; rest+=("$@"); break ;;
            -*)                    shift ;;
            *)                     rest+=("$1"); shift ;;
        esac
    done
    set -- "${rest[@]}"

    local action="${parsed_action:-$1}"
    if [ -z "$parsed_action" ]; then shift 2>/dev/null || true; fi
    local target_args=("$@")

    get_locale_vars() {
        local loc_str=""
        if [ -f /etc/locale.conf ]; then
            loc_str=$(grep -E '^[A-Z_]+=' /etc/locale.conf 2>/dev/null | tr '\n' ' ')
        elif [ -f /etc/default/locale ]; then
            loc_str=$(grep -E '^[A-Z_]+=' /etc/default/locale 2>/dev/null | tr '\n' ' ')
        elif [ -f /etc/env.d/02locale ]; then
            loc_str=$(grep -E '^[A-Z_]+=' /etc/env.d/02locale 2>/dev/null | tr '\n' ' ')
        fi
        if [ -z "$loc_str" ]; then
            loc_str="LANG=${LANG:-C.UTF-8}"
        fi
        echo "$loc_str" | sed 's/[[:space:]]*$//'
    }

    get_vc_keymap() {
        local km=""
        if [ -f /etc/vconsole.conf ]; then
            km=$(sed -n 's/^KEYMAP=\(.*\)/\1/p' /etc/vconsole.conf | tr -d '"' | tr -d "'")
        fi
        if [ -z "$km" ] && [ -f /etc/conf.d/keymaps ]; then
            km=$(sed -n 's/^keymap=\(.*\)/\1/p' /etc/conf.d/keymaps | tr -d '"' | tr -d "'")
        fi
        if [ -z "$km" ] && [ -f /etc/default/keyboard ]; then
            km=$(sed -n 's/^XKBLAYOUT=\(.*\)/\1/p' /etc/default/keyboard | tr -d '"' | tr -d "'")
        fi
        echo "${km:-us}"
    }

    get_vc_toggle_keymap() {
        local km=""
        if [ -f /etc/vconsole.conf ]; then
            km=$(sed -n 's/^KEYMAP_TOGGLE=\(.*\)/\1/p' /etc/vconsole.conf | tr -d '"' | tr -d "'")
        fi
        echo "$km"
    }

    get_x11_var() {
        local var="$1" val=""
        if [ -f /etc/default/keyboard ]; then
            val=$(sed -n "s/^${var}=\(.*\)/\1/p" /etc/default/keyboard | tr -d '"' | tr -d "'")
        fi
        if [ -z "$val" ] && [ -f /etc/X11/xorg.conf.d/00-keyboard.conf ]; then
            local option_name=""
            case "$var" in
                XKBLAYOUT)  option_name="XkbLayout" ;;
                XKBMODEL)   option_name="XkbModel" ;;
                XKBVARIANT) option_name="XkbVariant" ;;
                XKBOPTIONS) option_name="XkbOptions" ;;
            esac
            if [ -n "$option_name" ]; then
                val=$(sed -n "s/.*Option[[:space:]]*\"${option_name}\"[[:space:]]*\"\(.*\)\".*/\1/p" /etc/X11/xorg.conf.d/00-keyboard.conf)
            fi
        fi
        echo "$val"
    }

    get_xkb_lst_file() {
        for f in /usr/share/X11/xkb/rules/evdev.lst /usr/share/X11/xkb/rules/base.lst; do
            [ -f "$f" ] && { echo "$f"; return 0; }
        done
        return 1
    }

    case "$action" in
        ""|status)
            notice "cat /etc/locale.conf /etc/default/keyboard"
            local sys_loc; sys_loc=$(get_locale_vars)
            local vc_km; vc_km=$(get_vc_keymap)
            local vc_tog; vc_tog=$(get_vc_toggle_keymap)
            local x11_lay; x11_lay=$(get_x11_var XKBLAYOUT)
            local x11_mod; x11_mod=$(get_x11_var XKBMODEL)
            local x11_var; x11_var=$(get_x11_var XKBVARIANT)
            local x11_opt; x11_opt=$(get_x11_var XKBOPTIONS)

            if [ -n "$json_mode" ] && [ "$json_mode" != "off" ]; then
                printf '{"SystemLocale":"%s","VCKeymap":"%s","VCKeymapToggle":"%s","X11Layout":"%s","X11Model":"%s","X11Variant":"%s","X11Options":"%s"}\n' \
                    "$sys_loc" "$vc_km" "$vc_tog" "$x11_lay" "$x11_mod" "$x11_var" "$x11_opt"
                return 0
            fi

            echo "   System Locale: $sys_loc"
            echo "       VC Keymap: $vc_km"
            [ -n "$vc_tog" ] && echo "VC Toggle Keymap: $vc_tog"
            echo "      X11 Layout: ${x11_lay:-(unset)}"
            echo "       X11 Model: ${x11_mod:-(unset)}"
            echo "     X11 Variant: ${x11_var:-(unset)}"
            echo "     X11 Options: ${x11_opt:-(unset)}"
            ;;

        show)
            local sys_loc; sys_loc=$(get_locale_vars)
            local vc_km; vc_km=$(get_vc_keymap)
            local vc_tog; vc_tog=$(get_vc_toggle_keymap)
            local x11_lay; x11_lay=$(get_x11_var XKBLAYOUT)
            local x11_mod; x11_mod=$(get_x11_var XKBMODEL)
            local x11_var; x11_var=$(get_x11_var XKBVARIANT)
            local x11_opt; x11_opt=$(get_x11_var XKBOPTIONS)

            local props=(
                "SystemLocale=$sys_loc"
                "VCKeymap=$vc_km"
                "VCKeymapToggle=$vc_tog"
                "X11Layout=$x11_lay"
                "X11Model=$x11_mod"
                "X11Variant=$x11_var"
                "X11Options=$x11_opt"
            )

            local p
            for p in "${props[@]}"; do
                if match_property "$p" "${properties[@]}"; then
                    [ "$value_only" -eq 1 ] && echo "${p#*=}" || echo "$p"
                fi
            done
            ;;

        set-locale)
            [ ${#target_args[@]} -eq 0 ] && die "set-locale requires at least one locale assignment"
            check_root
            notice "updating system locale configuration"

            local arg kv_args=()
            for arg in "${target_args[@]}"; do
                if [[ "$arg" == *"="* ]]; then
                    kv_args+=("$arg")
                else
                    kv_args+=("LANG=$arg")
                fi
            done

            touch /etc/locale.conf
            for arg in "${kv_args[@]}"; do
                local k="${arg%%=*}"
                local v="${arg#*=}"
                sed -i "/^${k}=/d" /etc/locale.conf
                echo "${k}=\"${v}\"" >> /etc/locale.conf
            done

            if command -v update-locale &>/dev/null; then
                update-locale "${kv_args[@]}" 2>/dev/null || true
            elif [ -f /etc/default/locale ]; then
                mkdir -p /etc/default
                touch /etc/default/locale
                for arg in "${kv_args[@]}"; do
                    local k="${arg%%=*}"
                    local v="${arg#*=}"
                    sed -i "/^${k}=/d" /etc/default/locale
                    echo "${k}=\"${v}\"" >> /etc/default/locale
                done
            fi

            if [ -d /etc/env.d ]; then
                for arg in "${kv_args[@]}"; do
                    local k="${arg%%=*}"
                    local v="${arg#*=}"
                    sed -i "/^${k}=/d" /etc/env.d/02locale 2>/dev/null || true
                    echo "${k}=\"${v}\"" >> /etc/env.d/02locale
                done
                command -v env-update &>/dev/null && env-update || true
            fi

            el_notify normal "preferences-desktop-locale" "Locale updated" "${kv_args[*]}" 2>/dev/null
            ;;

        set-keymap)
            local km="${target_args[0]}"
            local toggle_km="${target_args[1]}"
            [ -z "$km" ] && die "set-keymap requires a keymap name"
            check_root

            notice "updating VC keymap to $km"

            touch /etc/vconsole.conf
            sed -i '/^KEYMAP=/d' /etc/vconsole.conf
            echo "KEYMAP=\"$km\"" >> /etc/vconsole.conf
            if [ -n "$toggle_km" ]; then
                sed -i '/^KEYMAP_TOGGLE=/d' /etc/vconsole.conf
                echo "KEYMAP_TOGGLE=\"$toggle_km\"" >> /etc/vconsole.conf
            fi

            if [ -f /etc/conf.d/keymaps ]; then
                sed -i "s/^keymap=.*/keymap=\"$km\"/" /etc/conf.d/keymaps
            fi

            command -v loadkeys &>/dev/null && loadkeys "$km" 2>/dev/null || true
            "$RC_SERVICE_BIN" keymaps restart &>/dev/null || true

            if [ "$no_convert" -eq 0 ]; then
                notice "localectl set-x11-keymap $km"
                cmd_localectl --no-convert set-x11-keymap "$km" 2>/dev/null || true
            fi

            el_notify normal "preferences-desktop-keyboard" "Keymap updated" "VC Keymap: $km" 2>/dev/null
            ;;

        set-x11-keymap)
            local layout="${target_args[0]}"
            local model="${target_args[1]}"
            local variant="${target_args[2]}"
            local options="${target_args[3]}"
            [ -z "$layout" ] && die "set-x11-keymap requires a layout name"
            check_root

            notice "updating X11 keymap (layout=$layout model=$model variant=$variant options=$options)"

            mkdir -p /etc/default
            touch /etc/default/keyboard
            sed -i '/^XKBLAYOUT=/d' /etc/default/keyboard
            echo "XKBLAYOUT=\"$layout\"" >> /etc/default/keyboard
            sed -i '/^XKBMODEL=/d' /etc/default/keyboard
            echo "XKBMODEL=\"${model:-pc105}\"" >> /etc/default/keyboard
            sed -i '/^XKBVARIANT=/d' /etc/default/keyboard
            echo "XKBVARIANT=\"$variant\"" >> /etc/default/keyboard
            sed -i '/^XKBOPTIONS=/d' /etc/default/keyboard
            echo "XKBOPTIONS=\"$options\"" >> /etc/default/keyboard

            mkdir -p /etc/X11/xorg.conf.d
            cat > /etc/X11/xorg.conf.d/00-keyboard.conf <<EOF
# Generated by systemd-openrc-wrapper localectl
Section "InputClass"
        Identifier "system-keyboard"
        MatchIsKeyboard "on"
        Option "XkbLayout" "$layout"
        Option "XkbModel" "${model:-pc105}"
        Option "XkbVariant" "$variant"
        Option "XkbOptions" "$options"
EndSection
EOF

            if [ -n "$DISPLAY" ] && command -v setxkbmap &>/dev/null; then
                local xkb_cmd=(setxkbmap -layout "$layout")
                [ -n "$model" ]   && xkb_cmd+=(-model "$model")
                [ -n "$variant" ] && xkb_cmd+=(-variant "$variant")
                [ -n "$options" ] && xkb_cmd+=(-option "$options")
                "${xkb_cmd[@]}" 2>/dev/null || true
            fi

            if [ "$no_convert" -eq 0 ]; then
                notice "localectl set-keymap $layout"
                cmd_localectl --no-convert set-keymap "$layout" 2>/dev/null || true
            fi

            el_notify normal "preferences-desktop-keyboard" "X11 Keymap updated" "Layout: $layout" 2>/dev/null
            ;;

        list-locales)
            locale -a 2>/dev/null | sort -u
            ;;

        list-keymaps)
            find /usr/share/keymaps /usr/share/kbd/keymaps /lib/kbd/keymaps -name '*.map*' 2>/dev/null \
                | sed -E 's#.*/##; s/\.map(\.gz|\.bz2)?$//' | sort -u
            ;;

        list-x11-keymap-models)
            local lst_f; lst_f=$(get_xkb_lst_file)
            if [ -n "$lst_f" ]; then
                awk '/^! model/{flag=1; next} /^!/{flag=0} flag && NF {print $1}' "$lst_f" | sort -u
            fi
            ;;

        list-x11-keymap-layouts)
            local lst_f; lst_f=$(get_xkb_lst_file)
            if [ -n "$lst_f" ]; then
                awk '/^! layout/{flag=1; next} /^!/{flag=0} flag && NF {print $1}' "$lst_f" | sort -u
            fi
            ;;

        list-x11-keymap-variants)
            local lst_f; lst_f=$(get_xkb_lst_file)
            local target_lay="${target_args[0]}"
            if [ -n "$lst_f" ]; then
                if [ -n "$target_lay" ]; then
                    awk -v lay="$target_lay" '/^! variant/{flag=1; next} /^!/{flag=0} flag && $0 ~ lay ":" {print $1}' "$lst_f" | sort -u
                else
                    awk '/^! variant/{flag=1; next} /^!/{flag=0} flag && NF {print $1}' "$lst_f" | sort -u
                fi
            fi
            ;;

        list-x11-keymap-options)
            local lst_f; lst_f=$(get_xkb_lst_file)
            if [ -n "$lst_f" ]; then
                awk '/^! option/{flag=1; next} /^!/{flag=0} flag && NF {print $1}' "$lst_f" | sort -u
            fi
            ;;

        help)
            cat <<'EOF'
localectl [OPTIONS...] COMMAND ...

Query or change system locale and keyboard settings.

Commands:
  status                   Show current locale settings
  show                     Show properties of locale settings
  set-locale LOCALE...     Set system locale
  list-locales             Show known locales
  set-keymap MAP [MAP]     Set console and X11 keyboard mappings
  list-keymaps             Show known virtual console keyboard mappings
  set-x11-keymap LAYOUT [MODEL [VARIANT [OPTIONS]]]
                           Set X11 and console keyboard mappings
  list-x11-keymap-models   Show known X11 keyboard mapping models
  list-x11-keymap-layouts  Show known X11 keyboard mapping layouts
  list-x11-keymap-variants [LAYOUT]
                           Show known X11 keyboard mapping variants
  list-x11-keymap-options  Show known X11 keyboard mapping options

Options:
  -h --help                Show this help
     --version             Show package version
  -l --full                Do not ellipsize output
     --no-pager            Do not pipe output into a pager
     --no-ask-password     Do not prompt for password
  -H --host=[USER@]HOST    Operate on remote host
  -M --machine=CONTAINER   Operate on local container
     --no-convert          Don't convert keyboard mappings
  -p --property=NAME       Show only properties by this name
  -P NAME                  Equivalent to --value --property=NAME
  -a --all                 Show all properties, including empty ones
     --value               When showing properties, only print the value
     --json=pretty|short|off
                           Generate JSON output
  -j                     Same as --json=pretty on tty, --json=short otherwise

See the localectl(1) man page for details.
EOF
            ;;

        version)
            echo "systemd $VERSION (localectl OpenRC wrapper)"
            ;;

        *)
            el_error "localectl action '$action' is not implemented."
            exit 1
            ;;
    esac
}

# ===========================================================================
# loginctl (emulated for OpenRC)
# ===========================================================================
cmd_loginctl() {
    require_openrc

    local no_legend=0 no_pager=0 quiet=0 user_mode=0
    local properties=() value_only=0 all_flag=0 json_mode=""
    local kill_whom="" signal_val="" lines_val="" output_mode=""
    local host_val="" machine_val="" parsed_action=""
    local rest=()

    while [ $# -gt 0 ]; do
        case "$1" in
            --no-legend)           no_legend=1; shift ;;
            --no-pager|--no-ask-password|--full|-l) shift ;;
            -q|--quiet)            quiet=1; shift ;;
            --user)                user_mode=1; shift ;;
            -p|--property)         properties+=("$2"); shift 2 ;;
            --property=*)          properties+=("${1#*=}"); shift ;;
            -p*)                   properties+=("${1#-p}"); shift ;;
            -P)                    value_only=1; properties+=("$2"); shift 2 ;;
            -P*)                   value_only=1; properties+=("${1#-P}"); shift ;;
            --value)               value_only=1; shift ;;
            -a|--all)              all_flag=1; shift ;;
            -H|--host)             host_val="$2"; shift 2 ;;
            --host=*)              host_val="${1#*=}"; shift ;;
            -H*)                   host_val="${1#-H}"; shift ;;
            -M|--machine)          machine_val="$2"; shift 2 ;;
            --machine=*)           machine_val="${1#*=}"; shift ;;
            -M*)                   machine_val="${1#-M}"; shift ;;
            --kill-whom=*)         kill_whom="${1#*=}"; shift ;;
            --kill-whom)           kill_whom="$2"; shift 2 ;;
            -s|--signal)           signal_val="$2"; shift 2 ;;
            --signal=*)            signal_val="${1#*=}"; shift ;;
            -s*)                   signal_val="${1#-s}"; shift ;;
            -n|--lines)            lines_val="$2"; shift 2 ;;
            --lines=*)             lines_val="${1#*=}"; shift ;;
            -n*)                   lines_val="${1#-n}"; shift ;;
            --json=*)              json_mode="${1#*=}"; shift ;;
            --json)                [ -t 1 ] && json_mode="pretty" || json_mode="short"; shift ;;
            -j)                    [ -t 1 ] && json_mode="pretty" || json_mode="short"; shift ;;
            -o|--output)           output_mode="$2"; shift 2 ;;
            --output=*)            output_mode="${1#*=}"; shift ;;
            -o*)                   output_mode="${1#-o}"; shift ;;
            -h|--help|help)        parsed_action="help"; shift ;;
            --version|version)     parsed_action="version"; shift ;;
            --)                    shift; rest+=("$@"); break ;;
            -*)                    shift ;;
            *)                     rest+=("$1"); shift ;;
        esac
    done
    set -- "${rest[@]}"

    local action="${parsed_action:-$1}"
    if [ -z "$parsed_action" ]; then shift 2>/dev/null || true; fi
    local target_args=("$@")

    case "$action" in
        ""|list-sessions)
            notice "who"
            local count=0 lines=() json_arr=()
            local u tty_val rest_line uid seat sess_id
            local who_out; who_out=$(timeout 2 who 2>/dev/null)

            while read -r u tty_val rest_line; do
                [ -z "$u" ] && continue
                count=$((count + 1))
                sess_id="$count"
                uid=$(id -u "$u" 2>/dev/null || echo "1000")
                if [[ "$tty_val" == tty* || "$tty_val" == :* ]]; then
                    seat="seat0"
                else
                    seat="-"
                fi
                lines+=("$(printf '%7s %5s %-10s %-7s %-10s' "$sess_id" "$uid" "$u" "$seat" "$tty_val")")
                json_arr+=("{\"session\":\"$sess_id\",\"uid\":$uid,\"user\":\"$u\",\"seat\":\"$seat\",\"tty\":\"$tty_val\"}")
            done <<< "$who_out"

            if [ "$count" -eq 0 ]; then
                local fallback_user="${LOGNAME:-${USER:-$(id -un 2>/dev/null)}}"
                if [ -n "$fallback_user" ]; then
                    count=1
                    sess_id="1"
                    uid=$(id -u "$fallback_user" 2>/dev/null || echo "1000")
                    seat="seat0"
                    tty_val="${DISPLAY:-tty7}"
                    lines+=("$(printf '%7s %5s %-10s %-7s %-10s' "$sess_id" "$uid" "$fallback_user" "$seat" "$tty_val")")
                    json_arr+=("{\"session\":\"$sess_id\",\"uid\":$uid,\"user\":\"$fallback_user\",\"seat\":\"$seat\",\"tty\":\"$tty_val\"}")
                fi
            fi

            if [ -n "$json_mode" ] && [ "$json_mode" != "off" ]; then
                local IFS=,
                echo "[${json_arr[*]}]"
                return 0
            fi

            if [ "$no_legend" -eq 0 ]; then
                printf '%7s %5s %-10s %-7s %-10s\n' "SESSION" "UID" "USER" "SEAT" "TTY"
            fi

            for l in "${lines[@]}"; do
                echo "$l"
            done

            if [ "$no_legend" -eq 0 ]; then
                echo
                echo "$count sessions listed."
            fi
            ;;

        list-users)
            notice "who"
            local count=0 lines=() json_arr=()
            local u uid
            local who_out; who_out=$(timeout 2 who 2>/dev/null)

            while read -r u; do
                [ -z "$u" ] && continue
                count=$((count + 1))
                uid=$(id -u "$u" 2>/dev/null || echo "1000")
                lines+=("$(printf '%5s %-10s' "$uid" "$u")")
                json_arr+=("{\"uid\":$uid,\"user\":\"$u\"}")
            done <<< "$(echo "$who_out" | awk '{print $1}' | sort -u)"

            if [ "$count" -eq 0 ]; then
                local fallback_user="${LOGNAME:-${USER:-$(id -un 2>/dev/null)}}"
                if [ -n "$fallback_user" ]; then
                    count=1
                    uid=$(id -u "$fallback_user" 2>/dev/null || echo "1000")
                    lines+=("$(printf '%5s %-10s' "$uid" "$fallback_user")")
                    json_arr+=("{\"uid\":$uid,\"user\":\"$fallback_user\"}")
                fi
            fi

            if [ -n "$json_mode" ] && [ "$json_mode" != "off" ]; then
                local IFS=,
                echo "[${json_arr[*]}]"
                return 0
            fi

            if [ "$no_legend" -eq 0 ]; then
                printf '%5s %-10s\n' "UID" "USER"
            fi

            for l in "${lines[@]}"; do
                echo "$l"
            done

            if [ "$no_legend" -eq 0 ]; then
                echo
                echo "$count users listed."
            fi
            ;;

        list-seats)
            if [ -n "$json_mode" ] && [ "$json_mode" != "off" ]; then
                echo '[{"seat":"seat0"}]'
                return 0
            fi

            if [ "$no_legend" -eq 0 ]; then
                printf '%-7s\n' "SEAT"
                echo "seat0"
                echo
                echo "1 seats listed."
            else
                echo "seat0"
            fi
            ;;

        show-session)
            local targets=("${target_args[@]}")
            [ ${#targets[@]} -eq 0 ] && targets=(1)
            local cur_user cur_uid cur_tty cur_disp sess p
            cur_user="${LOGNAME:-${USER:-$(id -un 2>/dev/null)}}"
            cur_uid=$(id -u "$cur_user" 2>/dev/null || echo "1000")
            cur_tty=$(tty 2>/dev/null | sed 's#/dev/##'; [ -z "$cur_tty" ] && echo "tty7")
            cur_disp="${DISPLAY:-:0}"

            for sess in "${targets[@]}"; do
                local props=(
                    "Id=${sess}"
                    "User=${cur_uid}"
                    "Name=${cur_user}"
                    "VTNr=${cur_tty#tty}"
                    "Seat=seat0"
                    "TTY=${cur_tty}"
                    "Display=${cur_disp}"
                    "Remote=no"
                    "Service=display-manager"
                    "Desktop=${XDG_CURRENT_DESKTOP:-XFCE}"
                    "Type=${XDG_SESSION_TYPE:-x11}"
                    "Class=user"
                    "Active=yes"
                    "State=active"
                    "IdleHint=no"
                )

                for p in "${props[@]}"; do
                    if match_property "$p" "${properties[@]}"; then
                        [ "$value_only" -eq 1 ] && echo "${p#*=}" || echo "$p"
                    fi
                done
            done
            ;;

        session-status)
            local targets=("${target_args[@]}")
            [ ${#targets[@]} -eq 0 ] && targets=(1)
            local cur_user cur_uid cur_tty cur_disp sess first=1
            cur_user="${LOGNAME:-${USER:-$(id -un 2>/dev/null)}}"
            cur_uid=$(id -u "$cur_user" 2>/dev/null || echo "1000")
            cur_tty=$(tty 2>/dev/null | sed 's#/dev/##'; [ -z "$cur_tty" ] && echo "tty7")
            cur_disp="${DISPLAY:-:0}"

            for sess in "${targets[@]}"; do
                [ "$first" -eq 0 ] && echo
                first=0
                echo "$sess - $cur_user ($cur_uid)"
                echo "           Since: $(uptime -s 2>/dev/null || date)"
                echo "          Leader: $$"
                echo "            Seat: seat0; $cur_tty"
                echo "         TTY/Disp: $cur_tty / $cur_disp"
                echo "         Service: display-manager"
                echo "           State: active"
                echo "            Unit: session-${sess}.scope"
            done
            ;;

        show-user)
            local targets=("${target_args[@]}")
            [ ${#targets[@]} -eq 0 ] && targets=("${LOGNAME:-${USER:-$(id -un 2>/dev/null)}}")
            local target_u target_uid target_name p

            for target_u in "${targets[@]}"; do
                target_uid=$(id -u "$target_u" 2>/dev/null || echo "$target_u")
                target_name=$(getent passwd "$target_u" 2>/dev/null | cut -d: -f1)
                [ -z "$target_name" ] && target_name="$target_u"

                local props=(
                    "UID=${target_uid}"
                    "Name=${target_name}"
                    "State=active"
                    "Sessions=1"
                    "Display=:0"
                    "Linger=no"
                )

                for p in "${props[@]}"; do
                    if match_property "$p" "${properties[@]}"; then
                        [ "$value_only" -eq 1 ] && echo "${p#*=}" || echo "$p"
                    fi
                done
            done
            ;;

        user-status)
            local targets=("${target_args[@]}")
            [ ${#targets[@]} -eq 0 ] && targets=("${LOGNAME:-${USER:-$(id -un 2>/dev/null)}}")
            local target_u target_uid first=1

            for target_u in "${targets[@]}"; do
                [ "$first" -eq 0 ] && echo
                first=0
                target_uid=$(id -u "$target_u" 2>/dev/null || echo "$target_u")
                echo "$target_u ($target_uid)"
                echo "           Since: $(uptime -s 2>/dev/null || date)"
                echo "           State: active"
                echo "        Sessions: 1"
                echo "          Linger: no"
            done
            ;;

        show-seat)
            local targets=("${target_args[@]}")
            [ ${#targets[@]} -eq 0 ] && targets=("seat0")
            local s_name p

            for s_name in "${targets[@]}"; do
                local props=(
                    "Id=${s_name}"
                    "ActiveSession=1"
                    "CanGraphical=yes"
                    "CanTTY=yes"
                )
                for p in "${props[@]}"; do
                    if match_property "$p" "${properties[@]}"; then
                        [ "$value_only" -eq 1 ] && echo "${p#*=}" || echo "$p"
                    fi
                done
            done
            ;;

        seat-status)
            local targets=("${target_args[@]}")
            [ ${#targets[@]} -eq 0 ] && targets=("seat0")
            local s_name first=1

            for s_name in "${targets[@]}"; do
                [ "$first" -eq 0 ] && echo
                first=0
                echo "$s_name"
                echo "        Sessions: 1"
                echo "     CanGraphical: yes"
                echo "           CanTTY: yes"
            done
            ;;

        activate)
            notice "chvt ${target_args[0]}"
            if [ -n "${target_args[0]}" ] && [[ "${target_args[0]}" =~ ^[0-9]+$ ]]; then
                command -v chvt &>/dev/null && chvt "${target_args[0]}" 2>/dev/null
            fi
            ;;

        lock-session|lock-sessions)
            if [ "${SYSTEMD_OPENRC_WRAPPER_LOCK_RECURSION:-0}" -eq 1 ]; then
                notice "lock session request acknowledged (recursion guard)"
                return 0
            fi
            notice "xdg-screensaver lock / loginctl lock-session"
            if command -v xflock4 &>/dev/null; then
                xflock4 2>/dev/null &
            elif command -v xdg-screensaver &>/dev/null; then
                SYSTEMD_OPENRC_WRAPPER_LOCK_RECURSION=1 xdg-screensaver lock 2>/dev/null &
            fi
            ;;

        unlock-session|unlock-sessions)
            notice "unlock session request acknowledged"
            ;;

        attach|flush-devices)
            notice "seat device action '$action' acknowledged"
            ;;

        enable-linger|disable-linger)
            local targets=("${target_args[@]}")
            [ ${#targets[@]} -eq 0 ] && targets=("${LOGNAME:-${USER:-$(id -un 2>/dev/null)}}")
            local target_u
            for target_u in "${targets[@]}"; do
                el_warning "loginctl $action for $target_u is not supported -- OpenRC has no lingering user manager."
            done
            ;;

        terminate-session|terminate-user|terminate-seat)
            check_root
            local targets=("${target_args[@]}")
            local target_item
            for target_item in "${targets[@]}"; do
                notice "pkill -u $target_item"
                pkill -u "$target_item" 2>/dev/null || true
            done
            ;;

        kill-session|kill-user)
            check_root
            local sig="${signal_val:-SIGTERM}"
            local targets=("${target_args[@]}")
            local target_item
            for target_item in "${targets[@]}"; do
                notice "pkill -${sig} -u $target_item"
                pkill -"${sig}" -u "$target_item" 2>/dev/null || true
            done
            ;;

        help)
            cat <<EOF
loginctl [OPTIONS...] COMMAND ...

Send control commands to or query the login manager.

Session Commands:
  list-sessions            List sessions
  session-status [ID...]   Show session status
  show-session [ID...]     Show properties of sessions or the manager
  activate [ID]            Activate a session
  lock-session [ID...]     Screen lock one or more sessions
  unlock-session [ID...]   Screen unlock one or more sessions
  lock-sessions            Screen lock all current sessions
  unlock-sessions          Screen unlock all current sessions
  terminate-session ID...  Terminate one or more sessions
  kill-session ID...       Send signal to processes of a session

User Commands:
  list-users               List users
  user-status [USER...]    Show user status
  show-user [USER...]      Show properties of users or the manager
  enable-linger [USER...]  Enable linger state of one or more users
  disable-linger [USER...] Disable linger state of one or more users
  terminate-user USER...   Terminate all sessions of one or more users
  kill-user USER...        Send signal to processes of a user

Seat Commands:
  list-seats               List seats
  seat-status [NAME...]    Show seat status
  show-seat [NAME...]      Show properties of seats or the manager
  attach NAME DEVICE...    Attach one or more devices to a seat
  flush-devices            Flush all device associations
  terminate-seat NAME...   Terminate all sessions on one or more seats

Options:
  -h --help                Show this help
     --version             Show package version
     --no-pager            Do not pipe output into a pager
     --no-legend           Do not show the headers and footers
     --no-ask-password     Don't prompt for password
  -H --host=[USER@]HOST    Operate on remote host
  -M --machine=CONTAINER   Operate on local container
  -p --property=NAME       Show only properties by this name
  -P NAME                  Equivalent to --value --property=NAME
  -a --all                 Show all properties, including empty ones
     --value               When showing properties, only print the value
  -l --full                Do not ellipsize output
     --kill-whom=WHOM      Whom to send signal to
  -s --signal=SIGNAL       Which signal to send
  -n --lines=INTEGER       Number of journal entries to show
     --json=MODE           Generate JSON output for list-sessions/users/seats
                             (takes one of pretty, short, or off)
  -j                       Same as --json=pretty on tty, --json=short otherwise
  -o --output=MODE         Change journal output mode (short, short-precise,
                             short-iso, short-iso-precise, short-full,
                             short-monotonic, short-unix, short-delta,
                             json, json-pretty, json-sse, json-seq, cat,
                             verbose, export, with-unit)

See the loginctl(1) man page for details.
EOF
            ;;

        version)
            echo "systemd $VERSION (loginctl OpenRC wrapper)"
            ;;

        *)
            el_error "loginctl action '$action' is not implemented."
            exit 1
            ;;
    esac
}

# ===========================================================================
# systemd-analyze / systemd-cat / systemd-notify / systemd-run
# systemd-tmpfiles / systemd-sysctl
# ===========================================================================
cmd_systemd_analyze() {
    local quiet=0 user_mode=0 json_mode="" no_pager=0 no_legend=0 table_flag=0
    local host_val="" machine_val="" parsed_action=""
    local rest=()

    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help|help)        parsed_action="help"; shift ;;
            --version|version)     parsed_action="version"; shift ;;
            -q|--quiet)            quiet=1; shift ;;
            --user)                user_mode=1; shift ;;
            --system|--global)     shift ;;
            --no-pager)            no_pager=1; shift ;;
            --no-legend)           no_legend=1; shift ;;
            --table)               table_flag=1; shift ;;
            -H|--host)             host_val="$2"; shift 2 ;;
            --host=*)              host_val="${1#*=}"; shift ;;
            -M|--machine)          machine_val="$2"; shift 2 ;;
            --machine=*)           machine_val="${1#*=}"; shift ;;
            --json=*)              json_mode="${1#*=}"; shift ;;
            --json)                json_mode="pretty"; shift ;;
            --root=*|--image=*|--image-policy=*|--recursive-errors=*|--offline=*|--threshold=*|--security-policy=*|--from-pattern=*|--to-pattern=*|--fuzz=*|--man=*|--generators=*|--instance=*|--iterations=*|--base-time=*|--profile=*|--unit=*|--scale-svg=*)
                                   shift ;;
            --root|--image|--image-policy|--recursive-errors|--offline|--threshold|--security-policy|--from-pattern|--to-pattern|--fuzz|--man|--generators|--instance|--iterations|--base-time|--profile|--unit|--scale-svg)
                                   shift 2 ;;
            --order|--require|--detailed|--tldr|-m|--mask)
                                   shift ;;
            --)                    shift; rest+=("$@"); break ;;
            -*)                    shift ;;
            *)                     rest+=("$1"); shift ;;
        esac
    done
    set -- "${rest[@]}"

    local action="${parsed_action:-$1}"
    if [ -z "$parsed_action" ]; then shift 2>/dev/null || true; fi
    local target_args=("$@")

    case "$action" in
        ""|time)
            notice "uptime"
            local up_sec
            up_sec=$(cut -d' ' -f1 /proc/uptime 2>/dev/null)
            if [ -n "$up_sec" ]; then
                local formatted_sec
                formatted_sec=$(printf '%.3f' "$up_sec" 2>/dev/null || echo "$up_sec")
                echo "Startup finished in ${formatted_sec}s (userspace = ${formatted_sec}s) [OpenRC system]"
            else
                uptime
            fi
            ;;

        blame)
            el_warning "systemd-analyze blame is half-emulated -- OpenRC does not track precise per-service boot timings, listing active services instead."
            notice "rc-status --all"
            local svc
            "$RC_STATUS_BIN" --all 2>/dev/null | awk '{print $1}' | grep -v '^Runlevel:' | grep -v '^$' | sort -u | while read -r svc; do
                printf '%10s %s\n' "n/a" "$svc.service"
            done
            ;;

        critical-chain)
            el_warning "systemd-analyze critical-chain is half-emulated -- showing runlevel default service chain."
            notice "rc-status default"
            echo "The time-critical chain of services on OpenRC (default runlevel):"
            "$RC_STATUS_BIN" default 2>/dev/null || "$RC_STATUS_BIN" --all 2>/dev/null
            ;;

        plot)
            notice "systemd-analyze plot (generating minimal SVG graph)"
            cat <<'EOF'
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="800" height="150" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <text x="20" y="30" font-family="sans-serif" font-size="16" fill="black">OpenRC Boot Analysis Plot (systemd-openrc-wrapper)</text>
  <rect x="20" y="50" width="760" height="40" fill="#4a90e2" rx="5"/>
  <text x="30" y="75" font-family="sans-serif" font-size="14" fill="white">OpenRC System Running</text>
</svg>
EOF
            ;;

        dot)
            notice "systemd-analyze dot"
            echo "digraph systemd {"
            local svc
            "$RC_STATUS_BIN" default 2>/dev/null | awk '{print $1}' | grep -v '^Runlevel:' | grep -v '^$' | while read -r svc; do
                echo "  \"$svc.service\" -> \"default.target\";"
            done
            echo "}"
            ;;

        dump)
            notice "rc-status --all"
            "$RC_STATUS_BIN" --all
            ;;

        cat-config)
            local item="${target_args[0]}"
            [ -z "$item" ] && die "cat-config requires a file or service name"
            local item_clean; item_clean=$(normalize_unit "$item")
            notice "cat-config $item"
            if [ -f "$item" ]; then
                cat "$item"
            elif [ -f "/etc/conf.d/$item_clean" ]; then
                echo "# /etc/conf.d/$item_clean"
                cat "/etc/conf.d/$item_clean"
            elif [ -f "/etc/init.d/$item_clean" ]; then
                echo "# /etc/init.d/$item_clean"
                cat "/etc/init.d/$item_clean"
            else
                el_error "Configuration file for '$item' not found."
                exit 1
            fi
            ;;

        unit-files)
            notice "rc-update show -v"
            exec "$RC_UPDATE_BIN" show -v
            ;;

        unit-paths)
            notice "unit-paths"
            echo "/etc/init.d"
            echo "/etc/conf.d"
            echo "/etc/runlevels"
            echo "/usr/local/etc/init.d"
            ;;

        exit-status)
            local filter="${target_args[0]}"
            local statuses=(
                "0 SUCCESS"
                "1 FAILURE"
                "2 INVALIDARGUMENT"
                "3 NOTIMPLEMENTED"
                "4 NOPERMISSION"
                "5 NOTINSTALLED"
                "6 NOTCONFIGURED"
                "7 NOTRUNNING"
                "64 USAGE"
                "65 DATAERR"
                "66 NOINPUT"
                "67 NOUSER"
                "68 NOHOST"
                "69 UNAVAILABLE"
                "70 SOFTWARE"
                "71 OSERR"
                "72 OSFILE"
                "73 CANTCREAT"
                "74 IOERR"
                "75 TEMPFAIL"
                "76 PROTOCOL"
                "77 NOPERM"
                "78 CONFIG"
                "126 CANNOTINVOKE"
                "127 NOTFOUND"
            )
            if [ -n "$filter" ]; then
                printf '%-7s %s\n' "STATUS" "NAME"
                local s
                for s in "${statuses[@]}"; do
                    if [[ "$s" == *"$filter"* ]]; then
                        printf '%-7s %s\n' ${s}
                    fi
                done
            else
                printf '%-7s %s\n' "STATUS" "NAME"
                local s
                for s in "${statuses[@]}"; do
                    printf '%-7s %s\n' ${s}
                done
            fi
            ;;

        capability)
            local filter="${target_args[0]}"
            local caps=(
                "0 cap_chown"
                "1 cap_dac_override"
                "2 cap_dac_read_search"
                "3 cap_fowner"
                "4 cap_fsetid"
                "5 cap_kill"
                "6 cap_setgid"
                "7 cap_setuid"
                "8 cap_setpcap"
                "9 cap_linux_immutable"
                "10 cap_net_bind_service"
                "11 cap_net_broadcast"
                "12 cap_net_admin"
                "13 cap_net_raw"
                "14 cap_ipc_lock"
                "15 cap_ipc_owner"
                "16 cap_sys_module"
                "17 cap_sys_rawio"
                "18 cap_sys_chroot"
                "19 cap_sys_ptrace"
                "20 cap_sys_pacct"
                "21 cap_sys_admin"
                "22 cap_sys_boot"
                "23 cap_sys_nice"
                "24 cap_sys_resource"
                "25 cap_sys_time"
                "26 cap_sys_tty_config"
                "27 cap_mknod"
                "28 cap_lease"
                "29 cap_audit_write"
                "30 cap_audit_control"
                "31 cap_setfcap"
                "32 cap_mac_override"
                "33 cap_mac_admin"
                "34 cap_syslog"
                "35 cap_wake_alarm"
                "36 cap_block_suspend"
                "37 cap_audit_read"
                "38 cap_perfmon"
                "39 cap_bpf"
                "40 cap_checkpoint_restore"
            )
            printf '%-5s %s\n' "NUM" "NAME"
            local c
            for c in "${caps[@]}"; do
                if [ -z "$filter" ] || [[ "$c" == *"$filter"* ]]; then
                    printf '%-5s %s\n' ${c}
                fi
            done
            ;;

        syscall-filter)
            local groups=(
                "@clock"
                "@cpu-emulation"
                "@debug"
                "@default"
                "@file-system"
                "@io-event"
                "@ipc"
                "@keyring"
                "@memlock"
                "@module"
                "@network-io"
                "@obsolete"
                "@privilege-escalation"
                "@process"
                "@raw-io"
                "@reboot"
                "@resources"
                "@sandbox"
                "@setuid"
                "@signal"
                "@swap"
                "@system-service"
                "@timer"
            )
            local g
            for g in "${groups[@]}"; do
                echo "$g"
            done
            ;;

        filesystems)
            notice "cat /proc/filesystems"
            cat /proc/filesystems 2>/dev/null | awk '{print $NF}' | sort -u
            ;;

        architectures)
            notice "uname -m"
            local arch; arch=$(uname -m 2>/dev/null || echo "x86-64")
            echo "$arch"
            echo "native"
            ;;

        smbios11)
            notice "cat /sys/class/dmi/id/*"
            if [ -d /sys/class/dmi/id ]; then
                local f
                for f in /sys/class/dmi/id/product_name /sys/class/dmi/id/sys_vendor /sys/class/dmi/id/product_version; do
                    [ -r "$f" ] && cat "$f" 2>/dev/null
                done
            fi
            ;;

        condition)
            notice "evaluating condition"
            return 0
            ;;

        compare-versions)
            local v1="${target_args[0]}"
            local op="${target_args[1]}"
            local v2="${target_args[2]}"
            if [ -z "$v2" ]; then
                v2="$op"
                op="gt"
            fi
            [ -z "$v1" ] || [ -z "$v2" ] && die "compare-versions requires two version strings"
            local dpkg_op="gt"
            case "$op" in
                "<"|"lt") dpkg_op="lt" ;;
                "<="|"le") dpkg_op="le" ;;
                "="|"=="|"eq") dpkg_op="eq" ;;
                "!="|"ne") dpkg_op="ne" ;;
                ">="|"ge") dpkg_op="ge" ;;
                ">"|"gt") dpkg_op="gt" ;;
            esac
            if command -v dpkg &>/dev/null; then
                if dpkg --compare-versions "$v1" "$dpkg_op" "$v2"; then
                    exit 0
                else
                    exit 1
                fi
            else
                local lowest
                lowest=$(printf '%s\n%s\n' "$v1" "$v2" | sort -V | head -n 1)
                case "$dpkg_op" in
                    gt) [ "$v1" != "$v2" ] && [ "$lowest" = "$v2" ] && exit 0 || exit 1 ;;
                    ge) [ "$lowest" = "$v2" ] && exit 0 || exit 1 ;;
                    lt) [ "$v1" != "$v2" ] && [ "$lowest" = "$v1" ] && exit 0 || exit 1 ;;
                    le) [ "$lowest" = "$v1" ] && exit 0 || exit 1 ;;
                    eq) [ "$v1" = "$v2" ] && exit 0 || exit 1 ;;
                    ne) [ "$v1" != "$v2" ] && exit 0 || exit 1 ;;
                esac
            fi
            ;;

        image-policy)
            local pol="${target_args[0]:-root=verity:usr=verity}"
            echo "POLICY: $pol"
            ;;

        calendar)
            local spec="${target_args[0]}"
            [ -z "$spec" ] && die "calendar requires a time spec"
            notice "validating calendar spec: $spec"
            date -d "$spec" "+Normalized form: %a %Y-%m-%d %H:%M:%S %Z" 2>/dev/null || echo "Normalized form: $spec"
            ;;

        timestamp)
            local ts="${target_args[0]}"
            [ -z "$ts" ] && die "timestamp requires a timestamp string"
            notice "validating timestamp: $ts"
            date -d "$ts" "+Normalized form: %a %Y-%m-%d %H:%M:%S %Z"
            ;;

        timespan)
            local span="${target_args[0]}"
            [ -z "$span" ] && die "timespan requires a timespan string"
            notice "validating timespan: $span"
            echo "Normalized form: $span"
            ;;

        verify)
            local f
            for f in "${target_args[@]}"; do
                if [ -f "$f" ]; then
                    if bash -n "$f" 2>/dev/null; then
                        echo "$f: OK"
                    else
                        echo "$f: syntax error"
                    fi
                else
                    echo "$f: file not found"
                fi
            done
            ;;

        security)
            notice "security review"
            printf '%-35s %-10s %s\n' "UNIT" "EXPOSURE" "PREDICATE"
            local svc
            "$RC_STATUS_BIN" default 2>/dev/null | awk '{print $1}' | grep -v '^Runlevel:' | grep -v '^$' | while read -r svc; do
                printf '%-35s %-10s %s\n' "$svc.service" "9.2" "UNPROTECTED"
            done
            ;;

        fdstore|malloc)
            notice "$action for ${target_args[*]}"
            echo "No file descriptor store or malloc stats available on OpenRC for ${target_args[*]}."
            ;;

        inspect-elf)
            local f="${target_args[0]}"
            [ -z "$f" ] && die "inspect-elf requires an ELF file path"
            notice "file -L $f"
            file -L "$f" 2>/dev/null || echo "$f: ELF file"
            ;;

        has-tpm2)
            if [ -c /dev/tpmrm0 ] || [ -c /dev/tpm0 ] || command -v tpm2_getcap &>/dev/null; then
                [ "$quiet" -eq 0 ] && echo "yes"
                exit 0
            else
                [ "$quiet" -eq 0 ] && echo "no"
                exit 1
            fi
            ;;

        pcrs|srk)
            notice "TPM operation $action"
            if command -v tpm2_pcrread &>/dev/null; then
                tpm2_pcrread 2>/dev/null || echo "TPM2 operation $action failed."
            else
                el_error "tpm2-tools not installed."
                exit 1
            fi
            ;;

        help)
            cat <<'EOF'
systemd-analyze [OPTIONS...] COMMAND ...

Profile systemd, show unit dependencies, check unit files.

Boot Analysis:
  [time]                     Print time required to boot the machine
  blame                      Print list of running units ordered by
                             time to init
  critical-chain [UNIT...]   Print a tree of the time critical chain
                             of units

Dependency Analysis:
  plot                       Output SVG graphic showing service
                             initialization
  dot [UNIT...]              Output dependency graph in dot(1) format
  dump [PATTERN...]          Output state serialization of service
                             manager

Configuration Files and Search Paths:
  cat-config NAME|PATH...    Show configuration file and drop-ins
  unit-files                 List files and symlinks for units
  unit-paths                 List load directories for units

Enumerate OS Concepts:
  exit-status [STATUS...]    List exit status definitions
  capability [CAP...]        List capability definitions
  syscall-filter [NAME...]   List syscalls in seccomp filters
  filesystems [NAME...]      List known filesystems
  architectures [NAME...]    List known architectures
  smbios11                   List strings passed via SMBIOS Type #11

Expression Evaluation:
  condition CONDITION...     Evaluate conditions and asserts
  compare-versions VERSION1 [OP] VERSION2
                             Compare two version strings
  image-policy POLICY...     Analyze image policy string

Clock & Time:
  calendar SPEC...           Validate repetitive calendar time
                             events
  timestamp TIMESTAMP...     Validate a timestamp
  timespan SPAN...           Validate a time span

Unit & Service Analysis:
  verify FILE...             Check unit files for correctness
  security [UNIT...]         Analyze security of unit
  fdstore SERVICE...         Show file descriptor store contents of service
  malloc [D-BUS SERVICE...]  Dump malloc stats of a D-Bus service

Executable Analysis:
  inspect-elf FILE...        Parse and print ELF package metadata

TPM Operations:
  has-tpm2                   Report whether TPM2 support is available
  pcrs [PCR...]              Show TPM2 PCRs and their names
  srk [>FILE]                Write TPM2 SRK (to FILE)

Options:
     --recursive-errors=MODE Control which units are verified
     --offline=BOOL          Perform a security review on unit file(s)
     --threshold=N           Exit with a non-zero status when overall
                             exposure level is over threshold value
     --security-policy=PATH  Use custom JSON security policy instead
                             of built-in one
     --json=pretty|short|off Generate JSON output of the security
                             analysis table, or plot's raw time data
     --no-pager              Do not pipe output into a pager
     --no-legend             Disable column headers and hints in plot
                             with either --table or --json=
     --system                Operate on system systemd instance
     --user                  Operate on user systemd instance
     --global                Operate on global user configuration
  -H --host=[USER@]HOST      Operate on remote host
  -M --machine=CONTAINER     Operate on local container
     --order                 Show only order in the graph
     --require               Show only requirement in the graph
     --from-pattern=GLOB     Show only origins in the graph
     --to-pattern=GLOB       Show only destinations in the graph
     --fuzz=SECONDS          Also print services which finished SECONDS
                             earlier than the latest in the branch
     --man[=BOOL]            Do [not] check for existence of man pages
     --generators[=BOOL]     Do [not] run unit generators
                             (requires privileges)
     --instance=NAME         Specify fallback instance name for template units
     --iterations=N          Show the specified number of iterations
     --base-time=TIMESTAMP   Calculate calendar times relative to
                             specified time
     --profile=name|PATH     Include the specified profile in the
                             security review of the unit(s)
     --unit=UNIT             Evaluate conditions and asserts of unit
     --table                 Output plot's raw time data as a table
     --scale-svg=FACTOR      Stretch x-axis of plot by FACTOR (default: 1.0)
     --detailed              Add more details to SVG plot,
                             e.g. show activation timestamps
  -h --help                  Show this help
     --version               Show package version
  -q --quiet                 Do not emit hints
     --tldr                  Skip comments and empty lines
     --root=PATH             Operate on an alternate filesystem root
     --image=PATH            Operate on disk image as filesystem root
     --image-policy=POLICY   Specify disk image dissection policy
  -m --mask                  Parse parameter as numeric capability mask

See the systemd-analyze(1) man page for details.
EOF
            ;;

        version)
            echo "systemd $VERSION (systemd-analyze OpenRC wrapper)"
            ;;

        *)
            el_error "systemd-analyze action '$action' is not implemented."
            exit 1
            ;;
    esac
}

cmd_systemd_cat() {
    local tag="systemd-cat" priority="" stderr_priority="" level_prefix="" namespace="" action=""
    local cmd=()

    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help)            action="help"; shift ;;
            --version)            action="version"; shift ;;
            -t|--identifier)      [ $# -ge 2 ] && tag="$2" && shift 2 || shift ;;
            --identifier=*)       tag="${1#*=}"; shift ;;
            -t*)                  tag="${1#-t}"; shift ;;
            -p|--priority)        [ $# -ge 2 ] && priority="$2" && shift 2 || shift ;;
            --priority=*)         priority="${1#*=}"; shift ;;
            -p*)                  priority="${1#-p}"; shift ;;
            --stderr-priority)    [ $# -ge 2 ] && stderr_priority="$2" && shift 2 || shift ;;
            --stderr-priority=*)  stderr_priority="${1#*=}"; shift ;;
            --level-prefix)       [ $# -ge 2 ] && level_prefix="$2" && shift 2 || shift ;;
            --level-prefix=*)     level_prefix="${1#*=}"; shift ;;
            --namespace)          [ $# -ge 2 ] && namespace="$2" && shift 2 || shift ;;
            --namespace=*)        namespace="${1#*=}"; shift ;;
            --)                   shift; cmd+=("$@"); break ;;
            -*)                   shift ;;
            *)                    cmd+=("$@"); break ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-cat [OPTIONS...] COMMAND ...

Execute process with stdout/stderr connected to the journal.

  -h --help                      Show this help
     --version                   Show package version
  -t --identifier=STRING         Set syslog identifier
  -p --priority=PRIORITY         Set priority value (0..7 or name)
     --stderr-priority=PRIORITY  Set priority value used for stderr
     --level-prefix=BOOL         Control whether level prefix shall be parsed
     --namespace=NAMESPACE       Connect to specified journal namespace

See the systemd-cat(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-cat OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    normalize_priority() {
        case "$1" in
            0|emerg|emergency) echo "emerg" ;;
            1|alert)           echo "alert" ;;
            2|crit|critical)   echo "crit" ;;
            3|err|error)       echo "err" ;;
            4|warning|warn)    echo "warning" ;;
            5|notice)          echo "notice" ;;
            6|info)            echo "info" ;;
            7|debug)           echo "debug" ;;
            *)                 echo "$1" ;;
        esac
    }

    [ -n "$namespace" ] && tag="$namespace/$tag"

    local norm_pri="" norm_err_pri=""
    [ -n "$priority" ] && norm_pri=$(normalize_priority "$priority")
    [ -n "$stderr_priority" ] && norm_err_pri=$(normalize_priority "$stderr_priority")

    notice "logger -t $tag${norm_pri:+ -p user.$norm_pri}"

    if [ ${#cmd[@]} -gt 0 ]; then
        if [ -n "$norm_err_pri" ] && [ "$norm_err_pri" != "$norm_pri" ]; then
            local stdout_opts=(-t "$tag")
            [ -n "$norm_pri" ] && stdout_opts+=(-p "user.$norm_pri")
            local stderr_opts=(-t "$tag")
            stderr_opts+=(-p "user.$norm_err_pri")

            "${cmd[@]}" > >(logger "${stdout_opts[@]}") 2> >(logger "${stderr_opts[@]}")
        else
            local logger_opts=(-t "$tag")
            [ -n "$norm_pri" ] && logger_opts+=(-p "user.$norm_pri")

            "${cmd[@]}" 2>&1 | logger "${logger_opts[@]}"
        fi
    else
        local logger_opts=(-t "$tag")
        local target_pri="${norm_pri:-$norm_err_pri}"
        [ -n "$target_pri" ] && logger_opts+=(-p "user.$target_pri")

        logger "${logger_opts[@]}"
    fi
}

cmd_systemd_notify() {
    local action=""
    local payload_vars=()
    local exec_mode=0
    local exec_cmd=()
    local uid=""

    while [ $# -gt 0 ]; do
        if [ "$exec_mode" -eq 0 ]; then
            case "$1" in
                -h|--help)        action="help"; shift ;;
                --version)        action="version"; shift ;;
                --booted)         action="booted"; shift ;;
                --ready)          payload_vars+=("READY=1"); shift ;;
                --reloading)      payload_vars+=("RELOADING=1"); shift ;;
                --stopping)       payload_vars+=("STOPPING=1"); shift ;;
                --status=*)       payload_vars+=("STATUS=${1#*=}"); shift ;;
                --status)         payload_vars+=("STATUS=$2"); shift 2 ;;
                --pid=*)
                    local p="${1#*=}"
                    [ -z "$p" ] && p="$PPID"
                    payload_vars+=("MAINPID=$p"); shift ;;
                --pid)
                    if [ $# -ge 2 ] && [[ "$2" =~ ^[0-9]+$ ]]; then
                        payload_vars+=("MAINPID=$2"); shift 2
                    else
                        payload_vars+=("MAINPID=$PPID"); shift
                    fi ;;
                --uid=*)          uid="${1#*=}"; shift ;;
                --uid)            uid="$2"; shift 2 ;;
                --fd=*)           payload_vars+=("FDSTORE=1"); shift ;;
                --fd)             payload_vars+=("FDSTORE=1"); shift 2 ;;
                --fdname=*)       payload_vars+=("FDNAME=${1#*=}"); shift ;;
                --fdname)         payload_vars+=("FDNAME=$2"); shift 2 ;;
                --no-block)       shift ;;
                --exec)           exec_mode=1; shift ;;
                \;)               shift ;;
                *=*)              payload_vars+=("$1"); shift ;;
                -*)               shift ;;
                *)                shift ;;
            esac
        else
            if [ "$1" = ";" ] || [ "$1" = "\;" ]; then
                shift
                exec_cmd+=("$@")
                break
            elif [[ "$1" == *=* ]]; then
                payload_vars+=("$1")
                shift
            else
                exec_cmd+=("$@")
                break
            fi
        fi
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-notify [OPTIONS...] [VARIABLE=VALUE...]
systemd-notify [OPTIONS...] --exec [VARIABLE=VALUE...] ; CMDLINE...

Notify the init system about service status updates.

  -h --help            Show this help
     --version         Show package version
     --ready           Inform the service manager about service start-up/reload
                       completion
     --reloading       Inform the service manager about configuration reloading
     --stopping        Inform the service manager about service shutdown
     --pid[=PID]       Set main PID of daemon
     --uid=USER        Set user to send from
     --status=TEXT     Set status text
     --booted          Check if the system was booted up with systemd
     --no-block        Do not wait until operation finished
     --exec            Execute command line separated by ';' once done
     --fd=FD           Pass specified file descriptor along with message
     --fdname=NAME     Name to assign to passed file descriptor(s)

See the systemd-notify(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-notify OpenRC wrapper v$VERSION)"
            return 0
            ;;
        booted)
            # Return 1 as system is running OpenRC, not booted with systemd
            exit 1
            ;;
    esac

    local payload=""
    if [ ${#payload_vars[@]} -gt 0 ]; then
        local v
        for v in "${payload_vars[@]}"; do
            payload="${payload}${v}"$'\n'
        done
    fi

    if [ -n "$payload" ] && [ -n "${NOTIFY_SOCKET:-}" ]; then
        notice "sending notification to \$NOTIFY_SOCKET ($NOTIFY_SOCKET)"
        if command -v python3 &>/dev/null; then
            python3 -c '
import socket, sys, os
sp = os.environ.get("NOTIFY_SOCKET", "")
if sp:
    if sp.startswith("@"):
        sp = "\x00" + sp[1:]
    try:
        s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
        s.sendto(sys.argv[1].encode("utf-8"), sp)
    except Exception:
        pass
' "$payload" 2>/dev/null || true
        elif command -v python &>/dev/null; then
            python -c '
import socket, sys, os
sp = os.environ.get("NOTIFY_SOCKET", "")
if sp:
    if sp.startswith("@"):
        sp = "\x00" + sp[1:]
    try:
        s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
        s.sendto(sys.argv[1].encode("utf-8"), sp)
    except Exception:
        pass
' "$payload" 2>/dev/null || true
        elif command -v socat &>/dev/null; then
            local sp="$NOTIFY_SOCKET"
            if [[ "$sp" == @* ]]; then
                sp="ABSTRACT:${sp#@}"
            else
                sp="UNIX-SENDTO:$sp"
            fi
            printf '%s' "$payload" | socat - "$sp" 2>/dev/null || true
        fi
    elif [ -n "$payload" ]; then
        notice "(no NOTIFY_SOCKET set; notification payload captured: ${payload_vars[*]})"
    else
        notice "(no-op notification)"
    fi

    if [ ${#exec_cmd[@]} -gt 0 ]; then
        notice "exec ${exec_cmd[*]}"
        exec "${exec_cmd[@]}"
    fi

    exit 0
}

cmd_systemd_run() {
    local action="" user_mode=0 shell_mode=0 pty_mode=0 pipe_mode=0 quiet=0
    local wait_flag=0 same_dir=0 ignore_failure=0 detach_mode=1
    local unit_name="" description="" uid_val="" gid_val="" nice_val="" work_dir=""
    local delay_sec="" json_mode=""
    local env_vars=() cmd=()

    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help)            action="help"; shift ;;
            --version)            action="version"; shift ;;
            --user)               user_mode=1; shift ;;
            --system)             user_mode=0; shift ;;
            --scope)              detach_mode=0; shift ;;
            -t|--pty)             pty_mode=1; detach_mode=0; shift ;;
            -P|--pipe)            pipe_mode=1; detach_mode=0; shift ;;
            --wait)               wait_flag=1; detach_mode=0; shift ;;
            -S|--shell)           shell_mode=1; detach_mode=0; shift ;;
            -q|--quiet)           quiet=1; shift ;;
            -d|--same-dir)        same_dir=1; shift ;;
            --ignore-failure)     ignore_failure=1; shift ;;
            --no-ask-password|--slice-inherit|--no-block|-r|--remain-after-exit|--send-sighup|-G|--collect|--on-timezone-change|--on-clock-change)
                                  shift ;;
            -u|--unit)            [ $# -ge 2 ] && unit_name="$2" && shift 2 || shift ;;
            --unit=*)             unit_name="${1#*=}"; shift ;;
            -u*)                  unit_name="${1#-u}"; shift ;;
            --description)        [ $# -ge 2 ] && description="$2" && shift 2 || shift ;;
            --description=*)      description="${1#*=}"; shift ;;
            --uid)                [ $# -ge 2 ] && uid_val="$2" && shift 2 || shift ;;
            --uid=*)              uid_val="${1#*=}"; shift ;;
            --gid)                [ $# -ge 2 ] && gid_val="$2" && shift 2 || shift ;;
            --gid=*)              gid_val="${1#*=}"; shift ;;
            --nice)               [ $# -ge 2 ] && nice_val="$2" && shift 2 || shift ;;
            --nice=*)             nice_val="${1#*=}"; shift ;;
            --working-directory)  [ $# -ge 2 ] && work_dir="$2" && shift 2 || shift ;;
            --working-directory=*) work_dir="${1#*=}"; shift ;;
            -E|--setenv)          [ $# -ge 2 ] && env_vars+=("$2") && shift 2 || shift ;;
            --setenv=*)           env_vars+=("${1#*=}"); shift ;;
            -E*)                  env_vars+=("${1#-E}"); shift ;;
            --on-active|--on-boot|--on-startup|--on-unit-active|--on-unit-inactive|--on-calendar)
                                  [ $# -ge 2 ] && delay_sec="$2" && shift 2 || shift ;;
            --on-active=*|--on-boot=*|--on-startup=*|--on-unit-active=*|--on-unit-inactive=*|--on-calendar=*)
                                  delay_sec="${1#*=}"; shift ;;
            --json=*)             json_mode="${1#*=}"; shift ;;
            --json)               json_mode="pretty"; shift ;;
            -H|--host|-M|--machine|-p|--property|--slice|--expand-environment|--service-type|--background|--path-property|--socket-property|--timer-property)
                                  [ $# -ge 2 ] && shift 2 || shift ;;
            --host=*|--machine=*|--property=*|--slice=*|--expand-environment=*|--service-type=*|--background=*|--path-property=*|--socket-property=*|--timer-property=*)
                                  shift ;;
            --)                   shift; cmd+=("$@"); break ;;
            -*)                   shift ;;
            *)                    cmd+=("$@"); break ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-run [OPTIONS...] COMMAND [ARGUMENTS...]

Run the specified command in a transient scope or service.

  -h --help                       Show this help
     --version                    Show package version
     --no-ask-password            Do not prompt for password
     --user                       Run as user unit
  -H --host=[USER@]HOST           Operate on remote host
  -M --machine=CONTAINER          Operate on local container
     --scope                      Run this as scope rather than service
  -u --unit=UNIT                  Run under the specified unit name
  -p --property=NAME=VALUE        Set service or scope unit property
     --description=TEXT           Description for unit
     --slice=SLICE                Run in the specified slice
     --slice-inherit              Inherit the slice from the caller
     --expand-environment=BOOL    Control expansion of environment variables
     --no-block                   Do not wait until operation finished
  -r --remain-after-exit          Leave service around until explicitly stopped
     --wait                       Wait until service stopped again
     --send-sighup                Send SIGHUP when terminating
     --service-type=TYPE          Service type
     --uid=USER                   Run as system user
     --gid=GROUP                  Run as system group
     --nice=NICE                  Nice level
     --working-directory=PATH     Set working directory
  -d --same-dir                   Inherit working directory from caller
  -E --setenv=NAME[=VALUE]        Set environment variable
  -t --pty                        Run service on pseudo TTY as STDIN/STDOUT/
                                  STDERR
  -P --pipe                       Pass STDIN/STDOUT/STDERR directly to service
  -q --quiet                      Suppress information messages during runtime
     --json=pretty|short|off      Print unit name and invocation id as JSON
  -G --collect                    Unload unit after it ran, even when failed
  -S --shell                      Invoke a $SHELL interactively
     --ignore-failure             Ignore the exit status of the invoked process
     --background=COLOR           Set ANSI color for background

Path options:
     --path-property=NAME=VALUE   Set path unit property

Socket options:
     --socket-property=NAME=VALUE Set socket unit property

Timer options:
     --on-active=SECONDS          Run after SECONDS delay
     --on-boot=SECONDS            Run SECONDS after machine was booted up
     --on-startup=SECONDS         Run SECONDS after systemd activation
     --on-unit-active=SECONDS     Run SECONDS after the last activation
     --on-unit-inactive=SECONDS   Run SECONDS after the last deactivation
     --on-calendar=SPEC           Realtime timer
     --on-timezone-change         Run when the timezone changes
     --on-clock-change            Run when the realtime clock jumps
     --timer-property=NAME=VALUE  Set timer unit property

See the systemd-run(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-run OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    if [ "$shell_mode" -eq 1 ]; then
        cmd=("${SHELL:-/bin/bash}")
    fi

    if [ ${#cmd[@]} -eq 0 ]; then
        die "systemd-run: no command given"
    fi

    local target_unit="${unit_name:-run-r$RANDOM.service}"

    if [ ${#env_vars[@]} -gt 0 ]; then
        local ev
        for ev in "${env_vars[@]}"; do
            export "$ev" 2>/dev/null || true
        done
    fi

    if [ -n "$work_dir" ]; then
        cd "$work_dir" || die "systemd-run: failed to change directory to $work_dir"
    fi

    local exec_cmd=()
    if [ -n "$nice_val" ]; then
        exec_cmd+=(nice -n "$nice_val")
    fi

    if [ -n "$uid_val" ] || [ -n "$gid_val" ]; then
        if [ "$(id -u)" -eq 0 ]; then
            if command -v runuser &>/dev/null; then
                local ru_args=()
                [ -n "$uid_val" ] && ru_args+=(-u "$uid_val")
                [ -n "$gid_val" ] && ru_args+=(-g "$gid_val")
                exec_cmd+=(runuser "${ru_args[@]}" -- "${cmd[@]}")
            elif command -v sudo &>/dev/null; then
                local su_args=()
                [ -n "$uid_val" ] && su_args+=(-u "$uid_val")
                [ -n "$gid_val" ] && su_args+=(-g "$gid_val")
                exec_cmd+=(sudo "${su_args[@]}" -- "${cmd[@]}")
            else
                exec_cmd+=("${cmd[@]}")
            fi
        else
            exec_cmd+=("${cmd[@]}")
        fi
    else
        exec_cmd+=("${cmd[@]}")
    fi

    if [ "$detach_mode" -eq 1 ]; then
        el_warning "systemd-run is half-emulated on OpenRC: launching detached process in background."
        notice "setsid nohup ${exec_cmd[*]} &"
        if [ "$quiet" -eq 0 ]; then
            if [ -n "$json_mode" ] && [ "$json_mode" != "off" ]; then
                printf '{"unit":"%s","invocation":"%s"}\n' "$target_unit" "$RANDOM$RANDOM"
            else
                echo "Running as unit: $target_unit"
            fi
        fi
        (
            if [ -n "$delay_sec" ]; then
                sleep "$delay_sec" 2>/dev/null || true
            fi
            setsid nohup "${exec_cmd[@]}" >/dev/null 2>&1 &
        )
    else
        if [ "$quiet" -eq 0 ]; then
            if [ -n "$json_mode" ] && [ "$json_mode" != "off" ]; then
                printf '{"unit":"%s","invocation":"%s"}\n' "$target_unit" "$RANDOM$RANDOM"
            elif [ "$shell_mode" -eq 0 ]; then
                echo "Running as unit: $target_unit"
            fi
        fi
        if [ -n "$delay_sec" ]; then
            sleep "$delay_sec" 2>/dev/null || true
        fi
        local rc=0
        "${exec_cmd[@]}" || rc=$?
        if [ "$ignore_failure" -eq 1 ]; then
            exit 0
        else
            exit $rc
        fi
    fi
}

cmd_systemd_tmpfiles() {
    local action="" do_create=0 do_clean=0 do_remove=0 do_purge=0 do_cat_config=0
    local user_mode=0 boot_flag=0 graceful_flag=0 dry_run=0 tldr_flag=0 ignore_special=0
    local root_dir="" image_dir="" image_policy="" replace_path=""
    local prefixes=() exclude_prefixes=() config_files=()

    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help)            action="help"; shift ;;
            --version)            action="version"; shift ;;
            --create)             do_create=1; shift ;;
            --clean)              do_clean=1; shift ;;
            --remove)             do_remove=1; shift ;;
            --purge)              do_purge=1; shift ;;
            --cat-config)         do_cat_config=1; shift ;;
            --user)               user_mode=1; shift ;;
            --boot)               boot_flag=1; shift ;;
            --graceful)           graceful_flag=1; shift ;;
            --dry-run)            dry_run=1; shift ;;
            --tldr)               tldr_flag=1; shift ;;
            --no-pager)            shift ;;
            -E)                   ignore_special=1; shift ;;
            --prefix)             prefixes+=("$2"); shift 2 ;;
            --prefix=*)           prefixes+=("${1#*=}"); shift ;;
            --exclude-prefix)     exclude_prefixes+=("$2"); shift 2 ;;
            --exclude-prefix=*)   exclude_prefixes+=("${1#*=}"); shift ;;
            --root)               root_dir="$2"; shift 2 ;;
            --root=*)             root_dir="${1#*=}"; shift ;;
            --image)              image_dir="$2"; shift 2 ;;
            --image=*)            image_dir="${1#*=}"; shift ;;
            --image-policy)       image_policy="$2"; shift 2 ;;
            --image-policy=*)     image_policy="${1#*=}"; shift ;;
            --replace)            replace_path="$2"; shift 2 ;;
            --replace=*)          replace_path="${1#*=}"; shift ;;
            --)                   shift; config_files+=("$@"); break ;;
            -*)                   shift ;;
            *)                    config_files+=("$1"); shift ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-tmpfiles COMMAND [OPTIONS...] [CONFIGURATION FILE...]

Create, delete, and clean up files and directories.

Commands:
     --create               Create and adjust files and directories
     --clean                Clean up files and directories
     --remove               Remove files and directories marked for removal
     --purge                Delete files and directories marked for creation in
                            specified configuration files (careful!)
  -h --help                 Show this help
     --version              Show package version

Options:
     --user                 Execute user configuration
     --cat-config           Show configuration files
     --tldr                 Show non-comment parts of configuration files
     --boot                 Execute actions only safe at boot
     --graceful             Quietly ignore unknown users or groups
     --prefix=PATH          Only apply rules with the specified prefix
     --exclude-prefix=PATH  Ignore rules with the specified prefix
  -E                        Ignore rules prefixed with /dev, /proc, /run, /sys
     --root=PATH            Operate on an alternate filesystem root
     --image=PATH           Operate on disk image as filesystem root
     --image-policy=POLICY  Specify disk image dissection policy
     --replace=PATH         Treat arguments as replacement for PATH
     --dry-run              Just print what would be done
     --no-pager             Do not pipe output into a pager

See the systemd-tmpfiles(8) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-tmpfiles OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    local target_files=()
    if [ ${#config_files[@]} -gt 0 ]; then
        local cf
        for cf in "${config_files[@]}"; do
            if [ -f "$cf" ]; then
                target_files+=("$cf")
            elif [ -f "/etc/tmpfiles.d/$cf" ]; then
                target_files+=("/etc/tmpfiles.d/$cf")
            elif [ -f "/etc/tmpfiles.d/${cf}.conf" ]; then
                target_files+=("/etc/tmpfiles.d/${cf}.conf")
            elif [ -f "/run/tmpfiles.d/$cf" ]; then
                target_files+=("/run/tmpfiles.d/$cf")
            elif [ -f "/run/tmpfiles.d/${cf}.conf" ]; then
                target_files+=("/run/tmpfiles.d/${cf}.conf")
            elif [ -f "/usr/lib/tmpfiles.d/$cf" ]; then
                target_files+=("/usr/lib/tmpfiles.d/$cf")
            elif [ -f "/usr/lib/tmpfiles.d/${cf}.conf" ]; then
                target_files+=("/usr/lib/tmpfiles.d/${cf}.conf")
            elif [ -f "/lib/tmpfiles.d/$cf" ]; then
                target_files+=("/lib/tmpfiles.d/$cf")
            elif [ -f "/lib/tmpfiles.d/${cf}.conf" ]; then
                target_files+=("/lib/tmpfiles.d/${cf}.conf")
            fi
        done
    else
        local search_dirs=(/etc/tmpfiles.d /run/tmpfiles.d /usr/lib/tmpfiles.d /lib/tmpfiles.d)
        [ "$user_mode" -eq 1 ] && search_dirs=(/etc/user-tmpfiles.d ~/.config/user-tmpfiles.d)
        local d f
        for d in "${search_dirs[@]}"; do
            [ -d "$d" ] || continue
            for f in "$d"/*.conf; do
                [ -f "$f" ] && target_files+=("$f")
            done
        done
    fi

    if [ "$do_cat_config" -eq 1 ]; then
        notice "cat-config for tmpfiles.d"
        local f
        for f in "${target_files[@]}"; do
            echo "# $f"
            if [ "$tldr_flag" -eq 1 ]; then
                grep -v -E '^[[:space:]]*#' "$f" | grep -v -E '^[[:space:]]*$' || true
            else
                cat "$f"
            fi
            echo
        done
        return 0
    fi

    if [ "$do_create" -eq 0 ] && [ "$do_clean" -eq 0 ] && [ "$do_remove" -eq 0 ] && [ "$do_purge" -eq 0 ]; then
        do_create=1
    fi

    should_process_path() {
        local target_path="$1"
        if [ "$ignore_special" -eq 1 ]; then
            case "$target_path" in
                /dev/*|/proc/*|/run/*|/sys/*) return 1 ;;
            esac
        fi
        if [ ${#prefixes[@]} -gt 0 ]; then
            local matched=0 p
            for p in "${prefixes[@]}"; do
                if [[ "$target_path" == "$p"* ]]; then
                    matched=1
                    break
                fi
            done
            [ "$matched" -eq 0 ] && return 1
        fi
        if [ ${#exclude_prefixes[@]} -gt 0 ]; then
            local ep
            for ep in "${exclude_prefixes[@]}"; do
                if [[ "$target_path" == "$ep"* ]]; then
                    return 1
                fi
            done
        fi
        return 0
    }

    el_info "Processing tmpfiles configuration (create=$do_create remove=$do_remove clean=$do_clean purge=$do_purge)"
    notice "systemd-tmpfiles processing ${#target_files[@]} config file(s)"

    local f clean_type
    for f in "${target_files[@]}"; do
        [ -r "$f" ] || continue
        while read -r type path mode owner group age arg; do
            case "$type" in
                ""|\#*) continue ;;
            esac

            clean_type="${type%!}"
            path="${root_dir}${path}"

            should_process_path "$path" || continue

            if [ "$do_purge" -eq 1 ]; then
                if [ "$dry_run" -eq 1 ]; then
                    echo "Would purge: $path"
                else
                    rm -rf "$path" 2>/dev/null || true
                fi
                continue
            fi

            if [ "$do_remove" -eq 1 ]; then
                case "$clean_type" in
                    r)
                        if [ "$dry_run" -eq 1 ]; then echo "Would remove: $path"; else rm -f "$path" 2>/dev/null || true; fi
                        ;;
                    R|D)
                        if [ "$dry_run" -eq 1 ]; then echo "Would recursively remove: $path"; else rm -rf "$path" 2>/dev/null || true; fi
                        ;;
                esac
            fi

            if [ "$do_create" -eq 1 ]; then
                case "$clean_type" in
                    d|D|e|v|q|Q)
                        if [ "$dry_run" -eq 1 ]; then
                            echo "Would create directory: $path (mode=$mode owner=$owner group=$group)"
                        else
                            [ "$clean_type" = "D" ] && [ -d "$path" ] && rm -rf "${path:?}"/* 2>/dev/null || true
                            mkdir -p "$path" 2>/dev/null || true
                            [ -n "$mode" ]  && [ "$mode" != "-" ]  && chmod "$mode" "$path" 2>/dev/null || true
                            [ -n "$owner" ] && [ "$owner" != "-" ] && chown "$owner" "$path" 2>/dev/null || true
                            [ -n "$group" ] && [ "$group" != "-" ] && chgrp "$group" "$path" 2>/dev/null || true
                        fi
                        ;;
                    f|F|f+)
                        if [ "$dry_run" -eq 1 ]; then
                            echo "Would create file: $path"
                        else
                            mkdir -p "$(dirname "$path")" 2>/dev/null || true
                            if [ "$clean_type" = "F" ] || [ "$clean_type" = "f+" ]; then
                                [ -n "$arg" ] && [ "$arg" != "-" ] && printf '%s\n' "$arg" > "$path" 2>/dev/null || : > "$path"
                            else
                                [ -e "$path" ] || { [ -n "$arg" ] && [ "$arg" != "-" ] && printf '%s\n' "$arg" > "$path" 2>/dev/null || touch "$path" 2>/dev/null; }
                            fi
                            [ -n "$mode" ]  && [ "$mode" != "-" ]  && chmod "$mode" "$path" 2>/dev/null || true
                            [ -n "$owner" ] && [ "$owner" != "-" ] && chown "$owner" "$path" 2>/dev/null || true
                            [ -n "$group" ] && [ "$group" != "-" ] && chgrp "$group" "$path" 2>/dev/null || true
                        fi
                        ;;
                    p|p+)
                        if [ "$dry_run" -eq 1 ]; then
                            echo "Would create fifo: $path"
                        else
                            mkdir -p "$(dirname "$path")" 2>/dev/null || true
                            [ -e "$path" ] || mkfifo "$path" 2>/dev/null || true
                            [ -n "$mode" ]  && [ "$mode" != "-" ]  && chmod "$mode" "$path" 2>/dev/null || true
                            [ -n "$owner" ] && [ "$owner" != "-" ] && chown "$owner" "$path" 2>/dev/null || true
                            [ -n "$group" ] && [ "$group" != "-" ] && chgrp "$group" "$path" 2>/dev/null || true
                        fi
                        ;;
                    w|w+)
                        if [ "$dry_run" -eq 1 ]; then
                            echo "Would write to file: $path ($arg)"
                        else
                            if [ -f "$path" ] || [ "$clean_type" = "w+" ]; then
                                [ -n "$arg" ] && [ "$arg" != "-" ] && printf '%s\n' "$arg" >> "$path" 2>/dev/null || true
                            fi
                        fi
                        ;;
                    L|L+)
                        if [ "$dry_run" -eq 1 ]; then
                            echo "Would create symlink: $path -> $arg"
                        else
                            mkdir -p "$(dirname "$path")" 2>/dev/null || true
                            if [ "$clean_type" = "L+" ]; then
                                rm -f "$path" 2>/dev/null || true
                            fi
                            [ -e "$path" ] || [ -L "$path" ] || ln -s "$arg" "$path" 2>/dev/null || true
                        fi
                        ;;
                    C)
                        if [ "$dry_run" -eq 1 ]; then
                            echo "Would copy: $arg -> $path"
                        else
                            if [ -e "$arg" ] && [ ! -e "$path" ]; then
                                cp -a "$arg" "$path" 2>/dev/null || true
                            fi
                        fi
                        ;;
                    z|Z)
                        if [ "$dry_run" -eq 1 ]; then
                            echo "Would adjust permissions on $path"
                        else
                            if [ -e "$path" ]; then
                                local recurse=""
                                [ "$clean_type" = "Z" ] && recurse="-R"
                                [ -n "$mode" ]  && [ "$mode" != "-" ]  && chmod $recurse "$mode" "$path" 2>/dev/null || true
                                [ -n "$owner" ] && [ "$owner" != "-" ] && chown $recurse "$owner" "$path" 2>/dev/null || true
                                [ -n "$group" ] && [ "$group" != "-" ] && chgrp $recurse "$group" "$path" 2>/dev/null || true
                            fi
                        fi
                        ;;
                esac
            fi
        done < "$f"
    done

    if [ "$do_clean" -eq 1 ]; then
        el_debug "systemd-tmpfiles --clean completed."
    fi
}

cmd_systemd_sysctl() {
    local action="" cat_config=0 config_files=()
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            --cat-config) cat_config=1; shift ;;
            --prefix=*) shift ;;
            --prefix) [ $# -ge 2 ] && shift 2 || shift ;;
            --) shift; config_files+=("$@"); break ;;
            -*) shift ;;
            *) config_files+=("$1"); shift ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-sysctl [OPTIONS...] [CONFIGFILE...]

Configure kernel parameters at boot.

  -h --help             Show this help
     --version          Show package version
     --cat-config       Show configuration files
     --prefix=PATH      Only apply rules with the specified prefix
     --sysctl|-p        Apply sysctl settings
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-sysctl OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    if [ "$cat_config" -eq 1 ]; then
        notice "cat-config sysctl.d"
        local f
        for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf /lib/sysctl.d/*.conf /etc/sysctl.conf; do
            if [ -f "$f" ]; then
                echo "# $f"
                cat "$f" 2>/dev/null
                echo
            fi
        done
        return 0
    fi

    if command -v sysctl &>/dev/null; then
        if [ ${#config_files[@]} -gt 0 ]; then
            local f
            for f in "${config_files[@]}"; do
                notice "sysctl -p $f"
                sysctl -p "$f" 2>/dev/null || true
            done
            return 0
        fi
        notice "sysctl --system"
        exec sysctl --system
    fi
    el_error "sysctl binary not found -- systemd-sysctl cannot be emulated."
    exit 1
}

cmd_systemd_ac_power() {
    local verbose=0 low=0 action=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -v|--verbose) verbose=1; shift ;;
            -l|--low) low=1; shift ;;
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            *) shift ;;
        esac
    done
    case "$action" in
        help)
            cat <<'EOF'
systemd-ac-power [OPTIONS...]

Report whether system is connected to AC power.

  -h --help     Show this help
     --version  Show package version
  -v --verbose  Show state as text
  -l --low      Check if battery is discharging and low
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-ac-power OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    local on_ac=0 low_batt=0 discharging=0 ps
    for ps in /sys/class/power_supply/*; do
        [ -d "$ps" ] || continue
        local type online capacity status
        type=$(cat "$ps/type" 2>/dev/null)
        online=$(cat "$ps/online" 2>/dev/null)
        capacity=$(cat "$ps/capacity" 2>/dev/null)
        status=$(cat "$ps/status" 2>/dev/null)
        if [[ "$type" == "Mains" || "$type" == "ADP"* || "$type" == "AC"* ]]; then
            [ "$online" = "1" ] && on_ac=1
        fi
        if [[ "$type" == "Battery" ]]; then
            [ "$status" = "Discharging" ] && discharging=1
            if [ -n "$capacity" ] && [ "$capacity" -lt 15 ]; then
                low_batt=1
            fi
        fi
    done

    if [ "$low" -eq 1 ]; then
        if [ "$discharging" -eq 1 ] && [ "$low_batt" -eq 1 ]; then
            [ "$verbose" -eq 1 ] && echo "Battery is discharging and low."
            exit 0
        else
            [ "$verbose" -eq 1 ] && echo "Battery is not discharging and low."
            exit 1
        fi
    fi

    if [ "$on_ac" -eq 1 ]; then
        [ "$verbose" -eq 1 ] && echo "yes"
        exit 0
    else
        [ "$verbose" -eq 1 ] && echo "no"
        exit 1
    fi
}

cmd_systemd_inhibit() {
    local what="idle:sleep:shutdown:handle-power-key:handle-suspend-key:handle-hibernate-key:handle-lid-switch"
    local who="" why="" mode="block" list_flag=0 action="" cmd=()

    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            --no-ask-password|--no-pager|--no-legend) shift ;;
            --what=*) what="${1#*=}"; shift ;;
            --what) what="$2"; shift 2 ;;
            --who=*) who="${1#*=}"; shift ;;
            --who) who="$2"; shift 2 ;;
            --why=*) why="${1#*=}"; shift ;;
            --why) why="$2"; shift 2 ;;
            --mode=*) mode="${1#*=}"; shift ;;
            --mode) mode="$2"; shift 2 ;;
            --list) list_flag=1; shift ;;
            --) shift; cmd+=("$@"); break ;;
            -*) shift ;;
            *) cmd+=("$1"); shift ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-inhibit [OPTIONS...] COMMAND ...

Execute a process while inhibiting shutdown/sleep/idle.

  -h --help               Show this help
     --version            Show package version
     --no-ask-password    Do not attempt interactive authorization
     --no-pager           Do not pipe output into a pager
     --no-legend          Do not show the headers and footers
     --what=WHAT          Operations to inhibit, colon separated list of:
                          shutdown, sleep, idle, handle-power-key,
                          handle-suspend-key, handle-hibernate-key,
                          handle-lid-switch
     --who=STRING         A descriptive string who is inhibiting
     --why=STRING         A descriptive string why is being inhibited
     --mode=MODE          One of block, block-weak, or delay
     --list               List active inhibitors

See the systemd-inhibit(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-inhibit OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    if [ "$list_flag" -eq 1 ]; then
        notice "(no active logind inhibitors on OpenRC)"
        printf '%-15s %-10s %-5s %-25s %-20s %-5s %-5s\n' "WHO" "UID" "USER" "WHAT" "WHY" "MODE" "PID"
        echo "0 inhibitors listed."
        return 0
    fi

    if [ ${#cmd[@]} -eq 0 ]; then
        die "systemd-inhibit: no command given"
    fi

    notice "systemd-inhibit executing: ${cmd[*]} (inhibiting $what)"
    exec "${cmd[@]}"
}

cmd_systemd_machine_id_setup() {
    local root_dir="" commit_flag=0 print_flag=0 action="" image_dir="" image_policy=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            --root=*) root_dir="${1#*=}"; shift ;;
            --root) root_dir="$2"; shift 2 ;;
            --image=*) image_dir="${1#*=}"; shift ;;
            --image) image_dir="$2"; shift 2 ;;
            --image-policy=*) image_policy="${1#*=}"; shift ;;
            --image-policy) image_policy="$2"; shift 2 ;;
            --commit) commit_flag=1; shift ;;
            --print) print_flag=1; shift ;;
            *) shift ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-machine-id-setup [OPTIONS...]

Initialize /etc/machine-id from a random source.

  -h --help                 Show this help
     --version              Show package version
     --root=PATH            Operate on an alternate filesystem root
     --image=PATH           Operate on disk image as filesystem root
     --image-policy=POLICY  Specify disk image dissection policy
     --commit               Commit transient ID
     --print                Print used machine ID

See the systemd-machine-id-setup(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-machine-id-setup OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    local target_file="${root_dir}/etc/machine-id" id=""

    if [ -s "$target_file" ] && [ "$(cat "$target_file" 2>/dev/null)" != "uninitialized" ]; then
        id=$(cat "$target_file" 2>/dev/null | tr -d '\n\r')
    else
        check_root
        mkdir -p "$(dirname "$target_file")"
        if command -v dbus-genid &>/dev/null; then
            id=$(dbus-genid 2>/dev/null | tr -d '-')
        fi
        if [ -z "$id" ] && [ -f /proc/sys/kernel/random/uuid ]; then
            id=$(tr -d '-' < /proc/sys/kernel/random/uuid | tr -d '\n\r')
        fi
        if [ -z "$id" ]; then
            id=$(head -c 16 /dev/urandom | xxd -p | tr -d '\n\r' 2>/dev/null || true)
        fi
        if [ -n "$id" ]; then
            echo "$id" > "$target_file"
            notice "Initialized machine ID at $target_file: $id"
        else
            el_error "Failed to generate machine ID"
            exit 1
        fi
    fi

    if [ "$print_flag" -eq 1 ]; then
        echo "$id"
    fi
}

cmd_systemd_ask_password() {
    local echo_mode="mask" timeout_val="" prompt="Password:" action="" no_newline=0 no_output=0 rest=()

    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            -e|--echo) echo_mode="yes"; shift ;;
            --echo=*) echo_mode="${1#*=}"; shift ;;
            --echo) echo_mode="$2"; shift 2 ;;
            --timeout=*) timeout_val="${1#*=}"; shift ;;
            --timeout) timeout_val="$2"; shift 2 ;;
            -n) no_newline=1; shift ;;
            --no-output) no_output=1; shift ;;
            --emoji=*|--credential=*) shift ;;
            --emoji|--credential) shift 2 ;;
            --icon=*|--id=*|--keyname=*|--accept-cached|--multiple|--no-tty|--no-legend|--user|--system)
                shift ;;
            --icon|--id|--keyname)
                shift 2 ;;
            --) shift; rest+=("$@"); break ;;
            -*) shift ;;
            *) rest+=("$1"); shift ;;
        esac
    done
    set -- "${rest[@]}"

    case "$action" in
        help)
            cat <<'EOF'
systemd-ask-password [OPTIONS...] MESSAGE

Query the user for a passphrase, via the TTY or a UI agent.

  -h --help           Show this help
     --icon=NAME      Icon name
     --id=ID          Query identifier (e.g. "cryptsetup:/dev/sda5")
     --keyname=NAME   Kernel key name for caching passwords (e.g. "cryptsetup")
     --credential=NAME
                      Credential name for ImportCredential=, LoadCredential= or
                      SetCredential= credentials
     --timeout=SEC    Timeout in seconds
     --echo=yes|no|masked
                      Control whether to show password while typing (echo)
  -e --echo           Equivalent to --echo=yes
     --emoji=yes|no|auto
                      Show a lock and key emoji
     --no-tty         Ask question via agent even on TTY
     --accept-cached  Accept cached passwords
     --multiple       List multiple passwords if available
     --no-output      Do not print password to standard output
  -n                  Do not suffix password written to standard output with
                      newline
     --user           Ask only our own user's agents
     --system         Ask agents of the system and of all users

See the systemd-ask-password(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-ask-password OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    if [ $# -gt 0 ]; then
        prompt="$*"
    fi

    local pass=""
    if [ "$echo_mode" = "yes" ]; then
        read -r -p "$prompt " pass
    else
        read -r -s -p "$prompt " pass
        echo >&2
    fi

    if [ "$no_output" -eq 0 ]; then
        if [ "$no_newline" -eq 1 ]; then
            printf '%s' "$pass"
        else
            echo "$pass"
        fi
    fi
}

cmd_systemd_mount() {
    local do_umount=0 do_list=0 is_tmpfs=0 action="" mount_args=()
    local owner_val="" fs_type="" mount_opts=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            -u|--umount|--unmount) do_umount=1; shift ;;
            --list) do_list=1; shift ;;
            -T|--tmpfs) is_tmpfs=1; shift ;;
            -A) shift ;;
            --automount=*) shift ;;
            --automount) shift 2 ;;
            --owner=*) owner_val="${1#*=}"; shift ;;
            --owner) owner_val="$2"; shift 2 ;;
            -t|--type=*) fs_type="${1#*=}"; shift ;;
            -t|--type) fs_type="$2"; shift 2 ;;
            -o|--options=*) mount_opts="${1#*=}"; shift ;;
            -o|--options) mount_opts="$2"; shift 2 ;;
            --no-block|--no-pager|--no-legend|-l|--full|--no-ask-password|-q|--quiet|--discover|--bind-device|-G|--collect) shift ;;
            --json=*|--user|--description=*|--property=*|--fsck=*|--timeout-idle-sec=*|--automount-property=*) shift ;;
            --json|-H|--host|-M|--machine|--description|-p|--property|--fsck|--timeout-idle-sec|--automount-property) shift 2 ;;
            *) mount_args+=("$1"); shift ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-mount [OPTIONS...] WHAT [WHERE]
systemd-mount [OPTIONS...] --tmpfs [NAME] WHERE
systemd-mount [OPTIONS...] --list
systemd-mount [OPTIONS...] --umount WHAT|WHERE...

Establish a mount or auto-mount point transiently.

  -h --help                       Show this help
     --version                    Show package version
     --no-block                   Do not wait until operation finished
     --no-pager                   Do not pipe output into a pager
     --no-legend                  Do not show the headers
  -l --full                       Do not ellipsize output
     --no-ask-password            Do not prompt for password
  -q --quiet                      Suppress information messages during runtime
     --json=pretty|short|off      Generate JSON output
     --user                       Run as user unit
  -H --host=[USER@]HOST           Operate on remote host
  -M --machine=CONTAINER          Operate on local container
     --discover                   Discover mount device metadata
  -t --type=TYPE                  File system type
  -o --options=OPTIONS            Mount options
     --owner=USER                 Add uid= and gid= options for USER
     --fsck=no                    Don't run file system check before mount
     --description=TEXT           Description for unit
  -p --property=NAME=VALUE        Set mount unit property
     --automount=BOOL             Create an automount point
  -A                              Same as --automount=yes
     --timeout-idle-sec=SEC       Specify automount idle timeout
     --automount-property=NAME=VALUE
                                  Set automount unit property
     --bind-device                Bind automount unit to device
     --list                       List mountable block devices
  -u --umount                     Unmount mount points
  -G --collect                    Unload unit after it stopped, even when failed
  -T --tmpfs                      Create a new tmpfs on the mount point

See the systemd-mount(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-mount OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    if [ "$do_list" -eq 1 ]; then
        notice "lsblk"
        if command -v lsblk &>/dev/null; then
            exec lsblk
        else
            exec df -h
        fi
    fi

    if [ "$do_umount" -eq 1 ]; then
        check_root
        notice "umount ${mount_args[*]}"
        exec umount "${mount_args[@]}"
    fi

    check_root
    local opts=()
    [ -n "$fs_type" ] && opts+=(-t "$fs_type")

    if [ -n "$owner_val" ]; then
        local uid_val gid_val
        uid_val=$(id -u "$owner_val" 2>/dev/null || echo "$owner_val")
        gid_val=$(id -g "$owner_val" 2>/dev/null || echo "$owner_val")
        if [ -n "$mount_opts" ]; then
            mount_opts="${mount_opts},uid=${uid_val},gid=${gid_val}"
        else
            mount_opts="uid=${uid_val},gid=${gid_val}"
        fi
    fi

    [ -n "$mount_opts" ] && opts+=(-o "$mount_opts")

    if [ "$is_tmpfs" -eq 1 ]; then
        opts+=(-t tmpfs)
        if [ ${#mount_args[@]} -eq 1 ]; then
            notice "mount -t tmpfs tmpfs ${mount_args[0]}"
            exec mount "${opts[@]}" tmpfs "${mount_args[0]}"
        else
            notice "mount ${opts[*]} ${mount_args[*]}"
            exec mount "${opts[@]}" "${mount_args[@]}"
        fi
    else
        notice "mount ${opts[*]} ${mount_args[*]}"
        exec mount "${opts[@]}" "${mount_args[@]}"
    fi
}

cmd_systemd_umount() {
    local action=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            *) shift ;;
        esac
    done
    case "$action" in
        help)
            cat <<'EOF'
systemd-umount [OPTIONS...] WHAT|WHERE...

Unmount mount points.

  -h --help       Show this help
     --version    Show package version

See the systemd-mount(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-umount OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    check_root
    notice "umount ${ORIGINAL_ARGV[*]}"
    exec umount "${ORIGINAL_ARGV[@]}"
}

cmd_systemd_cgls() {
    local action=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            --no-pager|-a|--all|-u|--unit|--user-unit|-l|--full|-k) shift ;;
            -x|--xattr=*|-c|--cgroup-id=*) shift ;;
            -x|--xattr|-c|--cgroup-id|-M|--machine) shift 2 ;;
            *) shift ;;
        esac
    done
    case "$action" in
        help)
            cat <<'EOF'
systemd-cgls [OPTIONS...] [CGROUP...]

Recursively show control group contents.

  -h --help           Show this help
     --version        Show package version
     --no-pager       Do not pipe output into a pager
  -a --all            Show all groups, including empty
  -u --unit           Show the subtrees of specified system units
     --user-unit      Show the subtrees of specified user units
  -x --xattr=BOOL     Show cgroup extended attributes
  -c --cgroup-id=BOOL Show cgroup ID
  -l --full           Do not ellipsize output
  -k                  Include kernel threads in output
  -M --machine=NAME   Show container NAME

See the systemd-cgls(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-cgls OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    notice "ps aux (cgroup listing fallback)"
    if [ -d /sys/fs/cgroup ]; then
        find /sys/fs/cgroup -type d 2>/dev/null
    else
        ps aux
    fi
}

cmd_systemd_cgtop() {
    local action=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            -p|-t|-c|-m|-i|-r|--raw|-P|-k|-1|-b|--batch) shift ;;
            --order=*|--cpu=*|--recursive=*|--depth=*) shift ;;
            --order|--cpu|--recursive|--depth|-d|--delay|-n|--iterations|-M|--machine) shift 2 ;;
            *) shift ;;
        esac
    done
    case "$action" in
        help)
            cat <<'EOF'
systemd-cgtop [OPTIONS...] [CGROUP]

Show top control groups by their resource usage.

  -h --help           Show this help
     --version        Show package version
     --order=path|tasks|cpu|memory|io
                      Order by specified property
  -p                  Same as --order=path, order by path
  -t                  Same as --order=tasks, order by number of
                      tasks/processes
  -c                  Same as --order=cpu, order by CPU load
  -m                  Same as --order=memory, order by memory load
  -i                  Same as --order=io, order by IO load
  -r --raw            Provide raw (not human-readable) numbers
     --cpu[=percentage]
                      Show CPU usage as percentage (default)
     --cpu=time       Show CPU usage as time
  -P                  Count userspace processes instead of tasks (excl. kernel)
  -k                  Count all processes instead of tasks (incl. kernel)
     --recursive=BOOL Sum up process count recursively
  -d --delay=DELAY    Delay between updates
  -n --iterations=N   Run for N iterations before exiting
  -1                  Shortcut for --iterations=1
  -b --batch          Run in batch mode, accepting no input
     --depth=DEPTH    Maximum traversal depth (default: 3)
  -M --machine=       Show container

See the systemd-cgtop(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-cgtop OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    notice "top (cgroup top fallback)"
    exec top
}

cmd_systemd_confext() {
    local action="" subcmd=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            --no-pager|--no-legend|--force|--no-reload) shift ;;
            --mutable=*|--root=*|--json=*|--image-policy=*|--noexec=*) shift ;;
            --mutable|--root|--json|--image-policy|--noexec) shift 2 ;;
            -*) shift ;;
            *) [ -z "$subcmd" ] && subcmd="$1"; shift ;;
        esac
    done
    case "$action" in
        help)
            cat <<'EOF'
systemd-confext [OPTIONS...] COMMAND

Merge configuration extension images into /etc/.

Commands:
  status                  Show current merge status (default)
  merge                   Merge extensions into relevant hierarchies
  unmerge                 Unmerge extensions from relevant hierarchies
  refresh                 Unmerge/merge extensions again
  list                    List installed extensions
  -h --help               Show this help
     --version            Show package version

See the systemd-confext(8) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-confext OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac
    notice "systemd-confext ${subcmd:-status}"
    echo "No confext image overlays active on OpenRC."
}

cmd_systemd_sysext() {
    local action="" subcmd=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            --no-pager|--no-legend|--force|--no-reload) shift ;;
            --mutable=*|--root=*|--json=*|--image-policy=*|--noexec=*) shift ;;
            --mutable|--root|--json|--image-policy|--noexec) shift 2 ;;
            -*) shift ;;
            *) [ -z "$subcmd" ] && subcmd="$1"; shift ;;
        esac
    done
    case "$action" in
        help)
            cat <<'EOF'
systemd-sysext [OPTIONS...] COMMAND

Merge system extension images into /usr/ and /opt/.

Commands:
  status                  Show current merge status (default)
  merge                   Merge extensions into relevant hierarchies
  unmerge                 Unmerge extensions from relevant hierarchies
  refresh                 Unmerge/merge extensions again
  list                    List installed extensions
  -h --help               Show this help
     --version            Show package version

See the systemd-sysext(8) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-sysext OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac
    notice "systemd-sysext ${subcmd:-status}"
    echo "No sysext image overlays active on OpenRC."
}

cmd_systemd_creds() {
    local action="" subcmd=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            --no-pager|--no-legend|--system|-p|--pretty|-H|-T|--user|--allow-null) shift ;;
            --json=*|--transcode=*|--newline=*|--name=*|--timestamp=*|--not-after=*|--with-key=*|--tpm2-device=*|--tpm2-pcrs=*|--tpm2-public-key=*|--tpm2-public-key-pcrs=*|--tpm2-signature=*|--uid=*) shift ;;
            --json|--transcode|--newline|--name|--timestamp|--not-after|--with-key|--tpm2-device|--tpm2-pcrs|--tpm2-public-key|--tpm2-public-key-pcrs|--tpm2-signature|--uid) shift 2 ;;
            -*) shift ;;
            *) [ -z "$subcmd" ] && subcmd="$1"; shift ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-creds [OPTIONS...] COMMAND ...

Display and Process Credentials.

Commands:
  list                    Show list of passed credentials
  cat CREDENTIAL...       Show contents of specified credentials
  setup                   Generate credentials host key, if not existing yet
  encrypt INPUT OUTPUT    Encrypt plaintext credential file and write to
                          ciphertext credential file
  decrypt INPUT [OUTPUT]  Decrypt ciphertext credential file and write to
                          plaintext credential file

Options:
  -h --help               Show this help
     --version            Show package version
     --no-pager           Do not pipe output into a pager
     --no-legend          Do not show the headers and footers
     --json=pretty|short|off
                          Generate JSON output
     --system             Show credentials passed to system
     --transcode=base64|unbase64|hex|unhex
                          Transcode credential data
     --newline=auto|yes|no
                          Suffix output with newline
  -p --pretty             Output as SetCredentialEncrypted= line
     --name=NAME          Override filename included in encrypted credential
     --timestamp=TIME     Include specified timestamp in encrypted credential
     --not-after=TIME     Include specified invalidation time in encrypted
                          credential
     --with-key=host|tpm2|host+tpm2|null|auto|auto-initrd
                          Which keys to encrypt with
  -H                      Shortcut for --with-key=host
  -T                      Shortcut for --with-key=tpm2
     --tpm2-device=PATH
                          Pick TPM2 device
     --tpm2-pcrs=PCR1+PCR2+PCR3+…
                          Specify TPM2 PCRs to seal against (fixed hash)
     --tpm2-public-key=PATH
                          Specify PEM certificate to seal against
     --tpm2-public-key-pcrs=PCR1+PCR2+PCR3+…
                          Specify TPM2 PCRs to seal against (public key)
     --tpm2-signature=PATH
                          Specify signature for public key PCR policy
     --user               Select user-scoped credential encryption
     --uid=UID            Select user for scoped credentials
     --allow-null         Allow decrypting credentials with empty key

See the systemd-creds(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-creds OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    case "$subcmd" in
        has-tpm2)
            if [ -c /dev/tpmrm0 ] || [ -c /dev/tpm0 ]; then
                exit 0
            else
                exit 1
            fi
            ;;
        cat|show|list)
            notice "systemd-creds $subcmd"
            if [ $# -gt 0 ] && [ -f "$1" ]; then
                cat "$1"
            else
                echo "No credentials."
            fi
            ;;
        *)
            notice "systemd-creds $subcmd"
            echo "Credentials operation '$subcmd' completed."
            ;;
    esac
}

cmd_systemd_delta() {
    local action="" no_pager=0
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            --no-pager) no_pager=1; shift ;;
            --diff=*|--type=*) shift ;;
            --diff|--type|-t) shift 2 ;;
            -t*) shift ;;
            *) shift ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-delta [OPTIONS...] [SUFFIX...]

Find overridden configuration files.

  -h --help           Show this help
     --version        Show package version
     --no-pager       Do not pipe output into a pager
     --diff[=1|0]     Show a diff when overridden files differ
  -t --type=LIST...   Only display a selected set of override types

See the systemd-delta(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-delta OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    notice "systemd-delta (scanning configuration overrides)"
    local count=0
    if [ -d /etc/conf.d ]; then
        local f base
        for f in /etc/conf.d/*; do
            [ -f "$f" ] || continue
            base=$(basename "$f")
            if [ -f "/usr/share/factory/etc/conf.d/$base" ]; then
                echo "[OVERRIDDEN] /etc/conf.d/$base"
                count=$((count + 1))
            fi
        done
    fi
    echo
    echo "$count overridden configuration files found."
}

cmd_systemd_detect_virt() {
    local quiet=0 check_container=0 check_vm=0 list_types=0 action=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            -q|--quiet) quiet=1; shift ;;
            -c|--container) check_container=1; shift ;;
            -v|--vm) check_vm=1; shift ;;
            -r|--chroot|--private-users|--cvm) shift ;;
            --list|--list-cvm) list_types=1; shift ;;
            *) shift ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-detect-virt [OPTIONS...]

Detect execution in a virtualized environment.

  -h --help             Show this help
     --version          Show package version
  -c --container        Only detect whether we are run in a container
  -v --vm               Only detect whether we are run in a VM
  -r --chroot           Detect whether we are run in a chroot() environment
     --private-users    Only detect whether we are running in a user namespace
     --cvm              Only detect whether we are run in a confidential VM
  -q --quiet            Don't output anything, just set return value
     --list             List all known and detectable types of virtualization
     --list-cvm         List all known and detectable types of confidential 
                        virtualization

See the systemd-detect-virt(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-detect-virt OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    if [ "$list_types" -eq 1 ]; then
        echo "qemu kvm zvm vmware oracle microsoft xen bochs ch uml parallels bhyve qnx docker openvz lxc lxc-libvirt wsl systemd-nspawn podman rkt k8s"
        return 0
    fi

    local virt_type="none" virt_cat="none"

    if [ -f /.dockerenv ] || [ -f /run/.containerenv ]; then
        virt_type="docker"
        virt_cat="container"
    elif [ -d /proc/vz ] && [ ! -d /proc/bc ]; then
        virt_type="openvz"
        virt_cat="container"
    elif grep -q "lxc" /proc/1/cgroup 2>/dev/null; then
        virt_type="lxc"
        virt_cat="container"
    elif grep -qi "microsoft" /proc/version 2>/dev/null; then
        virt_type="wsl"
        virt_cat="container"
    elif [ -f /sys/class/dmi/id/sys_vendor ]; then
        local vendor
        vendor=$(cat /sys/class/dmi/id/sys_vendor 2>/dev/null)
        case "$vendor" in
            *QEMU*|*KVM*) virt_type="kvm"; virt_cat="vm" ;;
            *VirtualBox*) virt_type="oracle"; virt_cat="vm" ;;
            *VMware*)    virt_type="vmware"; virt_cat="vm" ;;
            *Microsoft*) virt_type="hyperv"; virt_cat="vm" ;;
            *Xen*)       virt_type="xen"; virt_cat="vm" ;;
        esac
    fi

    if [ "$virt_type" = "none" ] && [ "${SYSTEMD_OPENRC_WRAPPER_VIRT_RECURSION:-0}" -eq 0 ]; then
        local real_bin real_path script_canon target_canon
        script_canon=$(readlink -f "$SCRIPT_PATH" 2>/dev/null || echo "$SCRIPT_PATH")
        target_canon=$(readlink -f "$WRAPPER_TARGET" 2>/dev/null || echo "$WRAPPER_TARGET")
        for real_bin in $(type -a -p systemd-detect-virt 2>/dev/null); do
            real_path=$(readlink -f "$real_bin" 2>/dev/null || echo "$real_bin")
            if [ "$real_path" != "$script_canon" ] && [ "$real_path" != "$target_canon" ]; then
                virt_type=$(SYSTEMD_OPENRC_WRAPPER_VIRT_RECURSION=1 "$real_bin" 2>/dev/null || echo "none")
                [ "$virt_type" != "none" ] && virt_cat="vm"
                break
            fi
        done
    fi

    if [ "$check_container" -eq 1 ] && [ "$virt_cat" != "container" ]; then
        virt_type="none"
    elif [ "$check_vm" -eq 1 ] && [ "$virt_cat" != "vm" ]; then
        virt_type="none"
    fi

    if [ "$virt_type" != "none" ]; then
        [ "$quiet" -eq 0 ] && echo "$virt_type"
        exit 0
    else
        [ "$quiet" -eq 0 ] && echo "none"
        exit 1
    fi
}

cmd_systemd_escape() {
    local is_path=0 unescape=0 action="" template="" suffix_val="" rest=()

    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            -p|--path) is_path=1; shift ;;
            -u|--unescape) unescape=1; shift ;;
            --template=*) template="${1#*=}"; shift ;;
            --template) template="$2"; shift 2 ;;
            --suffix=*) suffix_val="${1#*=}"; shift ;;
            --suffix) suffix_val="$2"; shift 2 ;;
            --instance|-m|--mangle|-c|--expression) shift ;;
            --) shift; rest+=("$@"); break ;;
            -*) shift ;;
            *) rest+=("$1"); shift ;;
        esac
    done
    set -- "${rest[@]}"

    case "$action" in
        help)
            cat <<'EOF'
systemd-escape [OPTIONS...] [NAME...]

Escape strings for usage in systemd unit names.

  -h --help               Show this help
     --version            Show package version
     --suffix=SUFFIX      Unit suffix to append to escaped strings
     --template=TEMPLATE  Insert strings as instance into template
     --instance           With --unescape, show just the instance part
  -u --unescape           Unescape strings
  -m --mangle             Mangle strings
  -p --path               When escaping/unescaping assume the string is a path

See the systemd-escape(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-escape OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    escape_str() {
        local str="$1"
        if [ "$is_path" -eq 1 ]; then
            str=$(echo "$str" | sed -E 's#^/+##; s#/$##; s#//+#/#g')
            [ -z "$str" ] && { echo "-"; return 0; }
        fi
        local out="" i char hex
        for (( i=0; i<${#str}; i++ )); do
            char="${str:$i:1}"
            case "$char" in
                [a-zA-Z0-9_]) out="${out}${char}" ;;
                /) out="${out}-" ;;
                -) out="${out}\\x2d" ;;
                *)
                    hex=$(printf '%02x' "'$char")
                    out="${out}\\x${hex}"
                    ;;
            esac
        done
        if [ -n "$template" ]; then
            out=$(echo "$template" | sed "s/@/@${out}/")
        elif [ -n "$suffix_val" ]; then
            if [[ "$out" != *".${suffix_val}" ]]; then
                out="${out}.${suffix_val}"
            fi
        fi
        echo "$out"
    }

    unescape_str() {
        local str="$1"
        if [ "$is_path" -eq 1 ] && [ "$str" = "-" ]; then
            echo "/"
            return 0
        fi
        echo -e "$(echo "$str" | sed 's/-/\//g; s/\\x\([0-9a-fA-F]\{2\}\)/\\x\1/g')"
    }

    local arg
    for arg in "$@"; do
        if [ "$unescape" -eq 1 ]; then
            unescape_str "$arg"
        else
            escape_str "$arg"
        fi
    done
}

cmd_systemd_firstboot() {
    local root_dir="" locale_val="" tz_val="" host_val="" action=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            --root=*) root_dir="${1#*=}"; shift ;;
            --root) root_dir="$2"; shift 2 ;;
            --locale=*) locale_val="${1#*=}"; shift ;;
            --locale) locale_val="$2"; shift 2 ;;
            --timezone=*) tz_val="${1#*=}"; shift ;;
            --timezone) tz_val="$2"; shift 2 ;;
            --hostname=*) host_val="${1#*=}"; shift ;;
            --hostname) host_val="$2"; shift 2 ;;
            --setup-machine-id|--prompt*|--copy*|--force|--delete-root-password|--reset) shift ;;
            --image=*|--image-policy=*|--locale-messages=*|--keymap=*|--machine-id=*|--root-password=*|--root-password-file=*|--root-password-hashed=*|--root-shell=*|--kernel-command-line=*|--welcome=*) shift ;;
            --image|--image-policy|--locale-messages|--keymap|--machine-id|--root-password|--root-password-file|--root-password-hashed|--root-shell|--kernel-command-line|--welcome) shift 2 ;;
            *) shift ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-firstboot [OPTIONS...]

Configures basic settings of the system.

  -h --help                       Show this help
     --version                    Show package version
     --root=PATH                  Operate on an alternate filesystem root
     --image=PATH                 Operate on disk image as filesystem root
     --image-policy=POLICY        Specify disk image dissection policy
     --locale=LOCALE              Set primary locale (LANG=)
     --locale-messages=LOCALE     Set message locale (LC_MESSAGES=)
     --keymap=KEYMAP              Set keymap
     --timezone=TIMEZONE          Set timezone
     --hostname=NAME              Set hostname
     --setup-machine-id           Set a random machine ID
     --machine-id=ID              Set specified machine ID
     --root-password=PASSWORD     Set root password from plaintext password
     --root-password-file=FILE    Set root password from file
     --root-password-hashed=HASH  Set root password from hashed password
     --root-shell=SHELL           Set root shell
     --kernel-command-line=CMDLINE
                                  Set kernel command line
     --prompt-locale              Prompt the user for locale settings
     --prompt-keymap              Prompt the user for keymap settings
     --prompt-timezone            Prompt the user for timezone
     --prompt-hostname            Prompt the user for hostname
     --prompt-root-password       Prompt the user for root password
     --prompt-root-shell          Prompt the user for root shell
     --prompt                     Prompt for all of the above
     --copy-locale                Copy locale from host
     --copy-keymap                Copy keymap from host
     --copy-timezone              Copy timezone from host
     --copy-root-password         Copy root password from host
     --copy-root-shell            Copy root shell from host
     --copy                       Copy locale, keymap, timezone, root password
     --force                      Overwrite existing files
     --delete-root-password       Delete root password
     --welcome=no                 Disable the welcome text
     --reset                      Remove existing files

See the systemd-firstboot(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-firstboot OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    check_root
    if [ -n "$locale_val" ]; then
        notice "setting locale to $locale_val"
        mkdir -p "${root_dir}/etc"
        echo "LANG=\"$locale_val\"" > "${root_dir}/etc/locale.conf"
    fi
    if [ -n "$tz_val" ]; then
        notice "setting timezone to $tz_val"
        mkdir -p "${root_dir}/etc"
        ln -sf "/usr/share/zoneinfo/$tz_val" "${root_dir}/etc/localtime"
        echo "$tz_val" > "${root_dir}/etc/timezone"
    fi
    if [ -n "$host_val" ]; then
        notice "setting hostname to $host_val"
        mkdir -p "${root_dir}/etc"
        echo "$host_val" > "${root_dir}/etc/hostname"
    fi
}

cmd_systemd_hwdb() {
    local action=""
    if [ "$1" = "update" ]; then action="update"; shift;
    elif [ "$1" = "query" ]; then action="query"; shift; fi

    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            -s|--strict|--usr) shift ;;
            -r|--root=*) shift ;;
            -r|--root) shift 2 ;;
            *) shift ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-hwdb [OPTIONS...] COMMAND ...

Update or query the hardware database.

Commands:
  update          Update the hwdb database
  query MODALIAS  Query database and print result

Options:
  -h --help       Show this help
     --version    Show package version
  -s --strict     When updating, return non-zero exit value on any parsing error
     --usr        Generate in /usr/lib/udev instead of /etc/udev
  -r --root=PATH  Alternative root path in the filesystem

See the systemd-hwdb(8) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-hwdb OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    if [ "${SYSTEMD_OPENRC_WRAPPER_HWDB_RECURSION:-0}" -eq 1 ]; then
        notice "systemd-hwdb $action complete (recursion guard)"
        return 0
    fi

    if [ "$action" = "query" ]; then
        if command -v udevadm &>/dev/null && [ $# -gt 0 ]; then
            notice "udevadm hwdb --query $*"
            SYSTEMD_OPENRC_WRAPPER_HWDB_RECURSION=1 exec udevadm hwdb --query "$@"
        else
            echo "hwdb query completed."
            return 0
        fi
    elif [ "$action" = "update" ]; then
        check_root
        if command -v udevadm &>/dev/null; then
            notice "udevadm hwdb --update"
            SYSTEMD_OPENRC_WRAPPER_HWDB_RECURSION=1 exec udevadm hwdb --update
        else
            echo "hwdb update completed."
            return 0
        fi
    else
        echo "hwdb completed."
        return 0
    fi
}

cmd_systemd_id128() {
    local as_uuid=0 action="" subcmd="" value_only=0
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            -u|--uuid) as_uuid=1; shift ;;
            -P|--value) value_only=1; shift ;;
            -j|--json=*|--app-specific=*) shift ;;
            -j|--json|-p|--pretty|-a|--app-specific|--no-pager|--no-legend) shift ;;
            -*) shift ;;
            *) [ -z "$subcmd" ] && subcmd="$1"; shift ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-id128 [OPTIONS...] COMMAND

Generate and print 128-bit identifiers.

Commands:
  new                     Generate a new ID
  machine-id              Print the ID of current machine
  boot-id                 Print the ID of current boot
  invocation-id           Print the ID of current invocation
  var-partition-uuid      Print the UUID for the /var/ partition
  show [NAME|UUID]        Print one or more UUIDs
  help                    Show this help

Options:
  -h --help               Show this help
     --no-pager           Do not pipe output into a pager
     --no-legend          Do not show the headers and footers
     --json=FORMAT        Output inspection data in JSON (takes one of
                          pretty, short, off)
  -j                      Equivalent to --json=pretty (on TTY) or
                          --json=short (otherwise)
  -p --pretty             Generate samples of program code
  -P --value              Only print the value
  -a --app-specific=ID    Generate app-specific IDs
  -u --uuid               Output in UUID format

See the systemd-id128(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-id128 OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    format_id() {
        local hex="$1"
        if [ "$as_uuid" -eq 1 ] && [ ${#hex} -eq 32 ]; then
            printf '%s-%s-%s-%s-%s\n' "${hex:0:8}" "${hex:8:4}" "${hex:12:4}" "${hex:16:4}" "${hex:20:12}"
        else
            echo "$hex"
        fi
    }

    case "$subcmd" in
        ""|new)
            local id
            if [ -f /proc/sys/kernel/random/uuid ]; then
                id=$(tr -d '-' < /proc/sys/kernel/random/uuid | tr -d '\n\r')
            else
                id=$(head -c 16 /dev/urandom | xxd -p | tr -d '\n\r' 2>/dev/null || echo "00000000000000000000000000000000")
            fi
            format_id "$id"
            ;;
        machine-id)
            local id
            id=$(cat /etc/machine-id 2>/dev/null | tr -d '\n\r')
            [ -z "$id" ] && id="00000000000000000000000000000000"
            format_id "$id"
            ;;
        boot-id)
            local id
            id=$(cat /proc/sys/kernel/random/boot_id 2>/dev/null | tr -d '-' | tr -d '\n\r')
            [ -z "$id" ] && id="00000000000000000000000000000000"
            format_id "$id"
            ;;
        *)
            notice "systemd-id128 $subcmd"
            format_id "00000000000000000000000000000000"
            ;;
    esac
}

cmd_systemd_path() {
    local action="" suffix="" query=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            --no-pager) shift ;;
            --suffix=*) suffix="${1#*=}"; shift ;;
            --suffix) suffix="$2"; shift 2 ;;
            -*) shift ;;
            *) [ -z "$query" ] && query="$1"; shift ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-path [OPTIONS...] [NAME...]

Show system and user paths.

  -h --help             Show this help
     --version          Show package version
     --suffix=SUFFIX    Suffix to append to paths
     --no-pager         Do not pipe output into a pager

See the systemd-path(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-path OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    case "$query" in
        search-binaries) echo "/usr/local/bin:/usr/bin:/bin" ;;
        search-library-arch) echo "/usr/lib:/lib" ;;
        system-configuration) echo "/etc" ;;
        system-state) echo "/var/lib" ;;
        system-cache) echo "/var/cache" ;;
        system-logs) echo "/var/log" ;;
        user-configuration) echo "${XDG_CONFIG_HOME:-$HOME/.config}" ;;
        user-data) echo "${XDG_DATA_HOME:-$HOME/.local/share}" ;;
        user-cache) echo "${XDG_CACHE_HOME:-$HOME/.cache}" ;;
        *)
            echo "search-binaries: /usr/local/bin:/usr/bin:/bin"
            echo "system-configuration: /etc"
            echo "system-logs: /var/log"
            ;;
    esac
}

cmd_systemd_socket_activate() {
    local listen_addr="" action="" cmd=()
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            -l|--listen=*) listen_addr="${1#*=}"; shift ;;
            -l|--listen) listen_addr="$2"; shift 2 ;;
            -d|--datagram|--seqpacket|-a|--accept|--inetd) shift ;;
            -E|--setenv=*|--fdname=*) shift ;;
            -E|--setenv|--fdname) shift 2 ;;
            --) shift; cmd+=("$@"); break ;;
            -*) shift ;;
            *) cmd+=("$1"); shift ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-socket-activate [OPTIONS...]

Listen on sockets and launch child on connection.

Options:
  -h --help                  Show this help and exit
     --version               Print version string and exit
  -l --listen=ADDR           Listen for raw connections at ADDR
  -d --datagram              Listen on datagram instead of stream socket
     --seqpacket             Listen on SOCK_SEQPACKET instead of stream socket
  -a --accept                Spawn separate child for each connection
  -E --setenv=NAME[=VALUE]   Pass an environment variable to children
     --fdname=NAME[:NAME...] Specify names for file descriptors
     --inetd                 Enable inetd file descriptor passing protocol

See the systemd-socket-activate(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-socket-activate OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    if [ ${#cmd[@]} -eq 0 ]; then
        die "systemd-socket-activate: no command specified"
    fi

    notice "systemd-socket-activate running: ${cmd[*]}"
    exec "${cmd[@]}"
}

cmd_systemd_stdio_bridge() {
    local bus_path="/run/dbus/system_bus_socket" action=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            -p|--bus-path=*) bus_path="${1#*=}"; shift ;;
            -p|--bus-path) bus_path="$2"; shift 2 ;;
            --system|--user) shift ;;
            -M|--machine=*) shift ;;
            -M|--machine) shift 2 ;;
            *) shift ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-stdio-bridge [OPTIONS...]

Forward messages between a pipe or socket and a D-Bus bus.

  -h --help              Show this help
     --version           Show package version
  -p --bus-path=PATH     Path to the bus address (default: unix:path=/run/dbus/system_bus_socket)
     --system            Connect to system bus
     --user              Connect to user bus
  -M --machine=CONTAINER Name of local container to connect to
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-stdio-bridge OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    notice "proxying stdio to $bus_path"
    if command -v socat &>/dev/null; then
        exec socat - "UNIX-CONNECT:$bus_path"
    else
        el_error "socat binary not found -- cannot bridge stdio to D-Bus socket $bus_path"
        exit 1
    fi
}

cmd_systemd_sysusers() {
    local root_dir="" cat_config=0 action="" config_files=()
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            --cat-config) cat_config=1; shift ;;
            --tldr|--dry-run|--inline|--no-pager) shift ;;
            --root=*) root_dir="${1#*=}"; shift ;;
            --root) root_dir="$2"; shift 2 ;;
            --image=*|--image-policy=*|--replace=*) shift ;;
            --image|--image-policy|--replace) shift 2 ;;
            --) shift; config_files+=("$@"); break ;;
            -*) shift ;;
            *) config_files+=("$1"); shift ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-sysusers [OPTIONS...] [CONFIGURATION FILE...]

Creates system user accounts.

  -h --help                 Show this help
     --version              Show package version
     --cat-config           Show configuration files
     --tldr                 Show non-comment parts of configuration
     --root=PATH            Operate on an alternate filesystem root
     --image=PATH           Operate on disk image as filesystem root
     --image-policy=POLICY  Specify disk image dissection policy
     --replace=PATH         Treat arguments as replacement for PATH
     --dry-run              Just print what would be done
     --inline               Treat arguments as configuration lines
     --no-pager             Do not pipe output into a pager

See the systemd-sysusers.service(8) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-sysusers OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    local target_files=()
    if [ ${#config_files[@]} -gt 0 ]; then
        local cf
        for cf in "${config_files[@]}"; do
            [ -f "$cf" ] && target_files+=("$cf")
        done
    else
        local d f
        for d in /usr/lib/sysusers.d /etc/sysusers.d /run/sysusers.d /lib/sysusers.d; do
            [ -d "$d" ] || continue
            for f in "$d"/*.conf; do
                [ -f "$f" ] && target_files+=("$f")
            done
        done
    fi

    if [ "$cat_config" -eq 1 ]; then
        local f
        for f in "${target_files[@]}"; do
            echo "# $f"
            cat "$f" 2>/dev/null
            echo
        done
        return 0
    fi

    check_root
    local f entry_type clean_type name id gecos home shell
    for f in "${target_files[@]}"; do
        [ -r "$f" ] || continue
        while read -r entry_type name id gecos home shell; do
            case "$entry_type" in
                ""|\#*) continue ;;
            esac
            clean_type="${entry_type%!}"
            case "$clean_type" in
                g)
                    notice "groupadd -r $name"
                    if ! getent group "$name" &>/dev/null; then
                        if [ -n "$id" ] && [ "$id" != "-" ] && [[ "$id" =~ ^[0-9]+$ ]]; then
                            groupadd -r -g "$id" "$name" 2>/dev/null || groupadd -r "$name" 2>/dev/null || true
                        else
                            groupadd -r "$name" 2>/dev/null || true
                        fi
                    fi
                    ;;
                u)
                    notice "useradd -r $name"
                    if ! getent passwd "$name" &>/dev/null; then
                        local useradd_cmd=(useradd -r) uid_part="${id%%:*}" gid_part="${id#*:}"
                        if [ -n "$uid_part" ] && [ "$uid_part" != "-" ] && [[ "$uid_part" =~ ^[0-9]+$ ]]; then
                            useradd_cmd+=(-u "$uid_part")
                        fi
                        if [ -n "$gid_part" ] && [ "$gid_part" != "-" ] && [ "$gid_part" != "$id" ] && [[ "$gid_part" =~ ^[0-9]+$ ]]; then
                            useradd_cmd+=(-g "$gid_part")
                        fi
                        [ -n "$home" ] && [ "$home" != "-" ] && useradd_cmd+=(-d "$home") || useradd_cmd+=(-d /nonexistent)
                        [ -n "$shell" ] && [ "$shell" != "-" ] && useradd_cmd+=(-s "$shell") || useradd_cmd+=(-s /usr/sbin/nologin)
                        [ -n "$gecos" ] && [ "$gecos" != "-" ] && useradd_cmd+=(-c "$gecos")
                        useradd_cmd+=("$name")
                        "${useradd_cmd[@]}" 2>/dev/null || useradd -r "$name" 2>/dev/null || true
                    fi
                    ;;
                m)
                    notice "usermod -aG $id $name"
                    usermod -aG "$id" "$name" 2>/dev/null || true
                    ;;
            esac
        done < "$f"
    done
}

cmd_systemd_tty_ask_password_agent() {
    local action=""
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            --list|--query|--watch|--wall|--plymouth) shift ;;
            --console=*) shift ;;
            --console) shift 2 ;;
            *) shift ;;
        esac
    done
    case "$action" in
        help)
            cat <<'EOF'
systemd-tty-ask-password-agent [OPTIONS...]

Process system password requests.

  -h --help              Show this help
     --version           Show package version
     --list              Show pending password requests
     --query             Process pending password requests
     --watch             Continuously process password requests
     --wall              Continuously forward password requests to wall
     --plymouth          Ask question with Plymouth instead of on TTY
     --console[=DEVICE]  Ask question on /dev/console (or DEVICE if specified)
                         instead of the current TTY

See the systemd-tty-ask-password-agent(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-tty-ask-password-agent OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac
    notice "systemd-tty-ask-password-agent (no password requests pending)"
    return 0
}

cmd_systemd_vpick() {
    local action="" type_val="" version_val="" arch_val="" suffix_val="" print_mode="" resolve=0 patterns=()

    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help) action="help"; shift ;;
            --version) action="version"; shift ;;
            -B|--basename=*) shift ;;
            -B|--basename) shift 2 ;;
            -V) version_val="$2"; shift 2 ;;
            -A) arch_val="$2"; shift 2 ;;
            -S|--suffix=*) suffix_val="${1#*=}"; shift ;;
            -S|--suffix) suffix_val="$2"; shift 2 ;;
            -t|--type=*) type_val="${1#*=}"; shift ;;
            -t|--type) type_val="$2"; shift 2 ;;
            -p|--print=*) print_mode="${1#*=}"; shift ;;
            -p|--print) print_mode="$2"; shift 2 ;;
            --resolve=*) resolve=1; shift ;;
            --) shift; patterns+=("$@"); break ;;
            -*) shift ;;
            *) patterns+=("$1"); shift ;;
        esac
    done

    case "$action" in
        help)
            cat <<'EOF'
systemd-vpick [OPTIONS...] PATH...

Pick entry from versioned directory.

  -h --help            Show this help
     --version         Show package version

Lookup Keys:
  -B --basename=BASENAME
                       Look for specified basename
  -V VERSION           Look for specified version
  -A ARCH              Look for specified architecture
  -S --suffix=SUFFIX   Look for specified suffix
  -t --type=TYPE       Look for specified inode type

Output:
  -p --print=filename  Print selected filename rather than path
  -p --print=version   Print selected version rather than path
  -p --print=type      Print selected inode type rather than path
  -p --print=arch      Print selected architecture rather than path
  -p --print=tries     Print selected tries left/tries done rather than path
  -p --print=all       Print all of the above
     --resolve=yes     Canonicalize the result path

See the systemd-vpick(1) man page for details.
EOF
            return 0
            ;;
        version)
            echo "systemd 256 (systemd-vpick OpenRC wrapper v$VERSION)"
            return 0
            ;;
    esac

    local pat match=""
    for pat in "${patterns[@]}"; do
        if [ -e "$pat" ]; then
            echo "$pat"
            return 0
        fi
        match=$(ls -d $pat 2>/dev/null | sort -V | tail -n 1)
        if [ -n "$match" ]; then
            echo "$match"
            return 0
        fi
    done
    exit 1
}

# ===========================================================================
# Check Install / Install / Uninstall
# ===========================================================================
is_systemd_package() {
    local pkgs="$1" p
    for p in ${pkgs//,/ }; do
        if [[ "$p" == systemd* ]]; then
            return 0
        fi
    done
    return 1
}

do_check_install() {
    require_openrc 2>/dev/null || true
    el_info "Checking installation status of systemd command names across system..."
    echo

    local wrapper_real
    wrapper_real=$(readlink -f "$WRAPPER_TARGET" 2>/dev/null || readlink -f "$SCRIPT_PATH" 2>/dev/null)

    local name dir path target target_real dpkg_out dpkg_pkg found_any non_systemd_count=0
    local has_dpkg=0
    command -v dpkg-query &>/dev/null && has_dpkg=1

    for name in "${NAMES[@]}"; do
        found_any=0
        echo "[$name]"

        for dir in "${BINDIRS[@]}"; do
            path="$dir/$name"
            [ -e "$path" ] || [ -L "$path" ] || continue
            found_any=1

            target_real=$(readlink -f "$path" 2>/dev/null || echo "$path")

            dpkg_pkg=""
            if [ "$has_dpkg" -eq 1 ]; then
                dpkg_out=$(dpkg-query -S "$path" 2>/dev/null || dpkg-query -S "$target_real" 2>/dev/null || true)
                if [ -n "$dpkg_out" ]; then
                    dpkg_pkg=$(echo "$dpkg_out" | cut -d: -f1)
                fi
            fi

            if [ -L "$path" ]; then
                target=$(readlink "$path")
                if [ "$target_real" = "$wrapper_real" ] || [[ "$target" == *"systemd-openrc-wrapper"* ]]; then
                    if [ -n "$dpkg_pkg" ]; then
                        if is_systemd_package "$dpkg_pkg"; then
                            echo "  - $path -> $target (wrapper symlink: systemd-openrc-wrapper; original dpkg package: '$dpkg_pkg' [systemd])"
                        else
                            el_warning "  - $path -> $target (wrapper symlink: systemd-openrc-wrapper; original dpkg package: '$dpkg_pkg' [NOT from systemd!])"
                            non_systemd_count=$((non_systemd_count + 1))
                        fi
                    else
                        echo "  - $path -> $target (wrapper symlink: systemd-openrc-wrapper; no dpkg package registered)"
                    fi
                else
                    if [ -n "$dpkg_pkg" ]; then
                        if is_systemd_package "$dpkg_pkg"; then
                            echo "  - $path -> $target (symlink; dpkg package: '$dpkg_pkg' [systemd])"
                        else
                            el_warning "  - $path -> $target (symlink to other tool; dpkg package: '$dpkg_pkg' [NOT from systemd!])"
                            non_systemd_count=$((non_systemd_count + 1))
                        fi
                    else
                        el_warning "  - $path -> $target (symlink to external tool; no dpkg package [NOT from systemd!])"
                        non_systemd_count=$((non_systemd_count + 1))
                    fi
                fi
            else
                if [ -n "$dpkg_pkg" ]; then
                    if is_systemd_package "$dpkg_pkg"; then
                        echo "  - $path (binary/file; dpkg package: '$dpkg_pkg' [systemd])"
                    else
                        el_warning "  - $path (binary/file; dpkg package: '$dpkg_pkg' [NOT from systemd!])"
                        non_systemd_count=$((non_systemd_count + 1))
                    fi
                else
                    el_warning "  - $path (unmanaged binary/script; no dpkg package [NOT from systemd!])"
                    non_systemd_count=$((non_systemd_count + 1))
                fi
            fi
        done

        if [ "$found_any" -eq 0 ]; then
            echo "  - NOT installed in system (${BINDIRS[*]})"
        fi
        echo
    done

    if [ "$non_systemd_count" -gt 0 ]; then
        el_warning "Found $non_systemd_count binary location(s) that do not originate from systemd packages or point to non-systemd binaries."
    else
        el_info "All detected binary locations originate from systemd packages or systemd-openrc-wrapper."
    fi
}

do_test_compat() {
    if type is_openrc &>/dev/null; then
        if is_openrc; then is_openrc=1; else is_openrc=0; fi
    elif [ -z "${is_openrc+x}" ]; then
        if [ -d /run/openrc ] || [ -f /run/openrc/softlevel ] || command -v openrc &>/dev/null; then
            is_openrc=1
        else
            is_openrc=0
        fi
    fi

    if ((is_openrc)); then
        :
    else
        el_error "OpenRC is not running on this system. Cannot run compatibility tests."
        exit 1
    fi

    local passed=0 failed=0 total=0

    run_t() {
        local desc="$1" pattern="$2"; shift 2
        total=$((total + 1))
        local out rc=0
        out=$(SYSTEMD_OPENRC_WRAPPER_QUIET=1 "$@" 2>&1) || rc=$?
        if [ "$rc" -eq 0 ] && echo "$out" | grep -qE "$pattern"; then
            echo "$desc: OK"
            passed=$((passed + 1))
        else
            echo "$desc: FAILED"
            failed=$((failed + 1))
        fi
    }

    run_t_exit_any() {
        local desc="$1" pattern="$2"; shift 2
        total=$((total + 1))
        local out
        out=$(SYSTEMD_OPENRC_WRAPPER_QUIET=1 "$@" 2>&1 || true)
        if echo "$out" | grep -qE "$pattern"; then
            echo "$desc: OK"
            passed=$((passed + 1))
        else
            echo "$desc: FAILED"
            failed=$((failed + 1))
        fi
    }

    # systemctl
    run_t "systemctl --version" "systemd 256" cmd_systemctl --version
    run_t "systemctl --help" "systemctl \[OPTIONS" cmd_systemctl --help
    run_t "systemctl status" "(Started|Stopped|active|inactive|Runlevel|OpenRC)" cmd_systemctl status
    run_t_exit_any "systemctl is-active non-existent-unit" "(active|inactive)" cmd_systemctl is-active non-existent-unit
    run_t_exit_any "systemctl is-enabled non-existent-unit" "(enabled|disabled)" cmd_systemctl is-enabled non-existent-unit
    run_t_exit_any "systemctl is-failed" "(active|degraded|failed)" cmd_systemctl is-failed
    run_t_exit_any "systemctl is-system-running" "(running|degraded|unknown|starting)" cmd_systemctl is-system-running
    run_t "systemctl list-units" "(Started|Stopped|active|inactive|Runlevel)" cmd_systemctl list-units
    run_t "systemctl list-automounts" "(Started|Stopped|active|inactive|Runlevel)" cmd_systemctl list-automounts
    run_t "systemctl list-paths" "(Started|Stopped|active|inactive|Runlevel)" cmd_systemctl list-paths
    run_t "systemctl list-sockets" "(Started|Stopped|active|inactive|Runlevel)" cmd_systemctl list-sockets
    run_t "systemctl list-timers" "(Started|Stopped|active|inactive|Runlevel)" cmd_systemctl list-timers
    run_t "systemctl list-unit-files" "(enabled|disabled|started|stopped|\|)" cmd_systemctl list-unit-files
    run_t "systemctl list-machines" "\.host" cmd_systemctl list-machines
    run_t "systemctl list-jobs" "No jobs" cmd_systemctl list-jobs
    run_t "systemctl list-dependencies" "(Started|Stopped|active|inactive|Runlevel)" cmd_systemctl list-dependencies
    run_t "systemctl cancel" "" cmd_systemctl cancel
    run_t "systemctl show-environment" "PATH=" cmd_systemctl show-environment
    run_t "systemctl import-environment" "" cmd_systemctl import-environment
    run_t "systemctl set-environment" "" cmd_systemctl set-environment TEST_WRAPPER_VAR=1
    run_t "systemctl unset-environment" "" cmd_systemctl unset-environment TEST_WRAPPER_VAR
    run_t "systemctl show" "(Version=|ActiveState=|Features=)" cmd_systemctl show
    run_t "systemctl show -p Version" "Version=" cmd_systemctl show -p Version
    run_t "systemctl show -P Version" "^256" cmd_systemctl show -P Version
    run_t "systemctl get-default" "(default|sysinit|boot|nonetwork|shutdown|single)" cmd_systemctl get-default
    run_t "systemctl whoami" "^[a-zA-Z0-9_-]+$" cmd_systemctl whoami
    run_t "systemctl daemon-reload" "" cmd_systemctl daemon-reload
    run_t "systemctl daemon-reexec" "" cmd_systemctl daemon-reexec
    run_t "systemctl reset-failed" "" cmd_systemctl reset-failed
    run_t "systemctl preset" "presets are half-emulated" cmd_systemctl preset non-existent-unit
    run_t "systemctl preset-all" "presets are half-emulated" cmd_systemctl preset-all
    run_t "systemctl cat" "init.d" cmd_systemctl cat non-existent-unit
    run_t "systemctl help" "systemctl \[OPTIONS" cmd_systemctl help

    # journalctl
    run_t "journalctl --version" "journalctl OpenRC wrapper" cmd_journalctl --version
    run_t "journalctl --help" "journalctl \[OPTIONS" cmd_journalctl --help
    run_t "journalctl --disk-usage" "Archived and active journals take up" cmd_journalctl --disk-usage
    run_t "journalctl --list-boots" "0 [0-9a-f]{32}" cmd_journalctl --list-boots
    run_t "journalctl --list-namespaces" "default" cmd_journalctl --list-namespaces
    run_t "journalctl --fields" "_SYSTEMD_UNIT" cmd_journalctl --fields
    run_t "journalctl --field=_SYSTEMD_UNIT" "[a-zA-Z0-9_-]" cmd_journalctl --field=_SYSTEMD_UNIT
    run_t "journalctl --field=SYSLOG_IDENTIFIER" "[a-zA-Z0-9_-]" cmd_journalctl --field=SYSLOG_IDENTIFIER
    run_t "journalctl -n 1" "[a-zA-Z0-9]" cmd_journalctl -n 1
    run_t "journalctl -r -n 1" "[a-zA-Z0-9]" cmd_journalctl -r -n 1
    run_t_exit_any "journalctl -u cron" "[a-zA-Z0-9]" cmd_journalctl -u cron -n 1
    run_t_exit_any "journalctl -t sys" "[a-zA-Z0-9]" cmd_journalctl -t sys -n 1
    run_t_exit_any "journalctl -g test" "[a-zA-Z0-9]" cmd_journalctl -g test -n 1
    run_t "journalctl --vacuum-size=10M" "Vacuuming complete" cmd_journalctl --vacuum-size=10M
    run_t "journalctl --vacuum-files=1" "Vacuuming complete" cmd_journalctl --vacuum-files=1
    run_t "journalctl --vacuum-time=1d" "Vacuuming complete" cmd_journalctl --vacuum-time=1d
    run_t "journalctl --verify" "PASS:" cmd_journalctl --verify
    run_t "journalctl --sync" "Journal action sync completed" cmd_journalctl --sync
    run_t "journalctl --flush" "Journal action flush completed" cmd_journalctl --flush
    run_t "journalctl --rotate" "Journal action rotate completed" cmd_journalctl --rotate
    run_t "journalctl --header" "File: /var/log/syslog" cmd_journalctl --header
    run_t_exit_any "journalctl -k" "(Linux|boot|Kernel|dmesg|[0-9]+\.[0-9]+)" cmd_journalctl -k

    # hostnamectl
    run_t "hostnamectl status" "(Static hostname|Operating System|Kernel)" cmd_hostnamectl status
    run_t "hostnamectl --version" "hostnamectl OpenRC wrapper" cmd_hostnamectl --version
    run_t "hostnamectl --help" "hostnamectl \[OPTIONS" cmd_hostnamectl --help
    run_t "hostnamectl --json" "StaticHostname" cmd_hostnamectl --json
    run_t "hostnamectl hostname" "^[a-zA-Z0-9_.-]+$" cmd_hostnamectl hostname
    run_t "hostnamectl icon-name" "^[a-zA-Z0-9_.-]+$" cmd_hostnamectl icon-name
    run_t "hostnamectl chassis" "^[a-zA-Z0-9_.-]+$" cmd_hostnamectl chassis
    run_t "hostnamectl deployment" "^[a-zA-Z0-9_.-]*$" cmd_hostnamectl deployment
    run_t "hostnamectl location" "^[a-zA-Z0-9_.-]*$" cmd_hostnamectl location
    run_t "hostnamectl set-hostname --help" "hostnamectl \[OPTIONS" cmd_hostnamectl set-hostname --help
    run_t "hostnamectl set-icon-name" "^[a-zA-Z0-9_.-]*$" cmd_hostnamectl set-icon-name ""
    run_t "hostnamectl set-chassis" "^[a-zA-Z0-9_.-]*$" cmd_hostnamectl set-chassis ""
    run_t "hostnamectl set-deployment" "^[a-zA-Z0-9_.-]*$" cmd_hostnamectl set-deployment ""
    run_t "hostnamectl set-location" "^[a-zA-Z0-9_.-]*$" cmd_hostnamectl set-location ""

    # timedatectl
    run_t "timedatectl status" "(Local time|Universal time|Time zone)" cmd_timedatectl status
    run_t "timedatectl show" "Timezone=" cmd_timedatectl show
    run_t "timedatectl show -p Timezone" "Timezone=" cmd_timedatectl show -p Timezone
    run_t "timedatectl show -P Timezone" "^[A-Za-z0-9_/-]+$" cmd_timedatectl show -P Timezone
    run_t "timedatectl --version" "timedatectl OpenRC wrapper" cmd_timedatectl --version
    run_t "timedatectl --help" "timedatectl \[OPTIONS" cmd_timedatectl --help
    run_t "timedatectl --json" "Timezone" cmd_timedatectl --json
    run_t "timedatectl list-timezones" "UTC" cmd_timedatectl list-timezones
    run_t "timedatectl timesync-status" "(Server:|tracking|offset)" cmd_timedatectl timesync-status
    run_t "timedatectl show-timesync" "RootDistanceMaxUSec=" cmd_timedatectl show-timesync
    run_t "timedatectl ntp-servers" "informational on OpenRC" cmd_timedatectl ntp-servers
    run_t "timedatectl revert" "informational on OpenRC" cmd_timedatectl revert eth0

    # localectl
    run_t "localectl status" "System Locale:" cmd_localectl status
    run_t "localectl show" "SystemLocale=" cmd_localectl show
    run_t "localectl show -p VCKeymap" "VCKeymap=" cmd_localectl show -p VCKeymap
    run_t "localectl show -P VCKeymap" "^[a-zA-Z0-9_.-]*$" cmd_localectl show -P VCKeymap
    run_t "localectl --version" "localectl OpenRC wrapper" cmd_localectl --version
    run_t "localectl --help" "localectl \[OPTIONS" cmd_localectl --help
    run_t "localectl --json" "SystemLocale" cmd_localectl --json
    run_t "localectl list-locales" "(C|UTF-8|en|es|fr|de|locale)" cmd_localectl list-locales
    run_t_exit_any "localectl list-keymaps" "^[a-zA-Z0-9_.-]*$" cmd_localectl list-keymaps
    run_t "localectl list-x11-keymap-models" "(pc10[45]|model|[a-z])" cmd_localectl list-x11-keymap-models
    run_t "localectl list-x11-keymap-layouts" "(us|es|fr|de|layout|[a-z])" cmd_localectl list-x11-keymap-layouts
    run_t "localectl list-x11-keymap-variants" "(intl|variant|[a-z])" cmd_localectl list-x11-keymap-variants
    run_t "localectl list-x11-keymap-options" "(ctrl|caps|option|[a-z])" cmd_localectl list-x11-keymap-options

    # loginctl
    run_t "loginctl list-sessions" "(SESSION|UID|USER|seat)" cmd_loginctl list-sessions
    run_t "loginctl list-sessions --json" "session" cmd_loginctl list-sessions --json
    run_t "loginctl list-users" "(UID|USER)" cmd_loginctl list-users
    run_t "loginctl list-users --json" "user" cmd_loginctl list-users --json
    run_t "loginctl list-seats" "SEAT" cmd_loginctl list-seats
    run_t "loginctl list-seats --json" "seat" cmd_loginctl list-seats --json
    run_t "loginctl show-session" "Id=" cmd_loginctl show-session
    run_t "loginctl session-status" "State: active" cmd_loginctl session-status
    run_t "loginctl show-user" "UID=" cmd_loginctl show-user
    run_t "loginctl user-status" "State: active" cmd_loginctl user-status
    run_t "loginctl show-seat" "Id=" cmd_loginctl show-seat
    run_t "loginctl seat-status" "CanGraphical:" cmd_loginctl seat-status
    run_t "loginctl --version" "loginctl OpenRC wrapper" cmd_loginctl --version
    run_t "loginctl --help" "loginctl \[OPTIONS" cmd_loginctl --help
    run_t "loginctl activate" "chvt" cmd_loginctl activate 1
    run_t "loginctl lock-sessions" "" cmd_loginctl lock-sessions
    run_t "loginctl unlock-sessions" "acknowledged" cmd_loginctl unlock-sessions
    run_t "loginctl flush-devices" "acknowledged" cmd_loginctl flush-devices
    run_t "loginctl enable-linger" "not supported" cmd_loginctl enable-linger
    run_t "loginctl disable-linger" "not supported" cmd_loginctl disable-linger

    # systemd-analyze
    run_t "systemd-analyze time" "Startup finished" cmd_systemd_analyze time
    run_t "systemd-analyze blame" "service" cmd_systemd_analyze blame
    run_t "systemd-analyze critical-chain" "time-critical chain" cmd_systemd_analyze critical-chain
    run_t "systemd-analyze plot" "<svg" cmd_systemd_analyze plot
    run_t "systemd-analyze dot" "digraph" cmd_systemd_analyze dot
    run_t "systemd-analyze dump" "Runlevel:" cmd_systemd_analyze dump
    run_t "systemd-analyze unit-files" "(enabled|disabled|started|stopped|\|)" cmd_systemd_analyze unit-files
    run_t "systemd-analyze unit-paths" "/etc/init.d" cmd_systemd_analyze unit-paths
    run_t "systemd-analyze cat-config" "etc" cmd_systemd_analyze cat-config /etc/fstab
    run_t "systemd-analyze exit-status" "SUCCESS" cmd_systemd_analyze exit-status
    run_t "systemd-analyze capability" "cap_" cmd_systemd_analyze capability
    run_t "systemd-analyze syscall-filter" "@" cmd_systemd_analyze syscall-filter
    run_t "systemd-analyze filesystems" "[a-z0-9]" cmd_systemd_analyze filesystems
    run_t "systemd-analyze architectures" "(x86|arm|aarch|native|[a-z0-9_.-])" cmd_systemd_analyze architectures
    run_t "systemd-analyze smbios11" "" cmd_systemd_analyze smbios11
    run_t "systemd-analyze condition" "evaluating condition" cmd_systemd_analyze condition "ConditionPathExists=/etc/fstab"
    run_t "systemd-analyze calendar '2025-01-01'" "Normalized form:" cmd_systemd_analyze calendar "2025-01-01"
    run_t "systemd-analyze timestamp '2025-01-01'" "Normalized form:" cmd_systemd_analyze timestamp "2025-01-01"
    run_t "systemd-analyze timespan '1h'" "Normalized form:" cmd_systemd_analyze timespan "1h"
    run_t "systemd-analyze image-policy" "POLICY:" cmd_systemd_analyze image-policy
    run_t "systemd-analyze compare-versions 2.0 1.0" "^[[:space:]]*$" cmd_systemd_analyze compare-versions 2.0 1.0
    run_t "systemd-analyze verify" "OK" cmd_systemd_analyze verify /etc/fstab
    run_t "systemd-analyze security" "EXPOSURE" cmd_systemd_analyze security
    run_t "systemd-analyze fdstore" "No file descriptor store" cmd_systemd_analyze fdstore test.service
    run_t "systemd-analyze inspect-elf" "(ELF|executable|dynamically linked|statically linked)" cmd_systemd_analyze inspect-elf /bin/sh
    run_t_exit_any "systemd-analyze has-tpm2" "(yes|no)" cmd_systemd_analyze has-tpm2
    run_t "systemd-analyze --version" "systemd-analyze OpenRC wrapper" cmd_systemd_analyze --version
    run_t "systemd-analyze --help" "systemd-analyze \[OPTIONS" cmd_systemd_analyze --help

    # systemd-cat
    run_t "systemd-cat --version" "systemd-cat OpenRC wrapper" cmd_systemd_cat --version
    run_t "systemd-cat --help" "systemd-cat \[OPTIONS" cmd_systemd_cat --help
    run_t "systemd-cat exec" "logger" cmd_systemd_cat -t testtag echo "hello"

    # systemd-detect-virt
    run_t_exit_any "systemd-detect-virt" "(none|kvm|oracle|vmware|hyperv|xen|qemu|docker|lxc|wsl|openvz)" cmd_systemd_detect_virt
    run_t_exit_any "systemd-detect-virt --container" "(none|docker|lxc|wsl|openvz)" cmd_systemd_detect_virt --container
    run_t_exit_any "systemd-detect-virt --vm" "(none|kvm|oracle|vmware|hyperv|xen|qemu)" cmd_systemd_detect_virt --vm
    run_t "systemd-detect-virt --list" "(kvm|qemu|docker)" cmd_systemd_detect_virt --list
    run_t "systemd-detect-virt --help" "systemd-detect-virt \[OPTIONS" cmd_systemd_detect_virt --help

    # systemd-escape
    run_t "systemd-escape" "hello-world" cmd_systemd_escape "hello/world"
    run_t "systemd-escape --unescape" "hello/world" cmd_systemd_escape -u "hello-world"
    run_t "systemd-escape --path" "usr-bin" cmd_systemd_escape --path "/usr/bin"
    run_t "systemd-escape --template" "foo@hello-world" cmd_systemd_escape --template="foo@.service" "hello/world"
    run_t "systemd-escape --suffix" "hello-world" cmd_systemd_escape --suffix="service" "hello/world"
    run_t "systemd-escape --help" "systemd-escape \[OPTIONS" cmd_systemd_escape --help

    # systemd-id128
    run_t "systemd-id128 new" "[0-9a-f]{32}" cmd_systemd_id128 new
    run_t "systemd-id128 machine-id" "[0-9a-f]{32}" cmd_systemd_id128 machine-id
    run_t "systemd-id128 boot-id" "[0-9a-f]{32}" cmd_systemd_id128 boot-id
    run_t "systemd-id128 show" "[0-9a-f]{32}" cmd_systemd_id128 show
    run_t "systemd-id128 -u new" "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" cmd_systemd_id128 -u new
    run_t "systemd-id128 --help" "systemd-id128 \[OPTIONS" cmd_systemd_id128 --help

    # systemd-path
    run_t "systemd-path search-binaries" "/usr/bin" cmd_systemd_path search-binaries
    run_t "systemd-path search-library-arch" "/usr/lib" cmd_systemd_path search-library-arch
    run_t "systemd-path system-configuration" "/etc" cmd_systemd_path system-configuration
    run_t "systemd-path system-state" "/var/lib" cmd_systemd_path system-state
    run_t "systemd-path system-cache" "/var/cache" cmd_systemd_path system-cache
    run_t "systemd-path system-logs" "/var/log" cmd_systemd_path system-logs
    run_t "systemd-path user-configuration" "\.config" cmd_systemd_path user-configuration
    run_t "systemd-path user-data" "\.local/share" cmd_systemd_path user-data
    run_t "systemd-path user-cache" "\.cache" cmd_systemd_path user-cache
    run_t "systemd-path --help" "systemd-path \[OPTIONS" cmd_systemd_path --help

    # Additional systemd tooling
    run_t "systemd-ac-power --version" "systemd-ac-power OpenRC wrapper" cmd_systemd_ac_power --version
    run_t "systemd-ac-power --help" "systemd-ac-power \[OPTIONS" cmd_systemd_ac_power --help
    run_t_exit_any "systemd-ac-power -v" "(yes|no)" cmd_systemd_ac_power -v
    run_t "systemd-ask-password --version" "systemd-ask-password OpenRC wrapper" cmd_systemd_ask_password --version
    run_t "systemd-ask-password --help" "systemd-ask-password" cmd_systemd_ask_password --help
    run_t "systemd-cgls --version" "systemd-cgls OpenRC wrapper" cmd_systemd_cgls --version
    run_t "systemd-cgls --help" "systemd-cgls" cmd_systemd_cgls --help
    run_t "systemd-cgls exec" "(cgroup|sys|dev|root|proc|[a-zA-Z0-9])" cmd_systemd_cgls
    run_t "systemd-cgtop --version" "systemd-cgtop OpenRC wrapper" cmd_systemd_cgtop --version
    run_t "systemd-cgtop --help" "systemd-cgtop" cmd_systemd_cgtop --help
    run_t "systemd-confext status" "confext" cmd_systemd_confext status
    run_t "systemd-confext list" "confext" cmd_systemd_confext list
    run_t "systemd-confext merge" "confext" cmd_systemd_confext merge
    run_t "systemd-confext unmerge" "confext" cmd_systemd_confext unmerge
    run_t "systemd-confext refresh" "confext" cmd_systemd_confext refresh
    run_t "systemd-confext --version" "systemd-confext OpenRC wrapper" cmd_systemd_confext --version
    run_t "systemd-confext --help" "systemd-confext" cmd_systemd_confext --help
    run_t "systemd-sysext status" "sysext" cmd_systemd_sysext status
    run_t "systemd-sysext list" "sysext" cmd_systemd_sysext list
    run_t "systemd-sysext merge" "sysext" cmd_systemd_sysext merge
    run_t "systemd-sysext unmerge" "sysext" cmd_systemd_sysext unmerge
    run_t "systemd-sysext refresh" "sysext" cmd_systemd_sysext refresh
    run_t "systemd-sysext --version" "systemd-sysext OpenRC wrapper" cmd_systemd_sysext --version
    run_t "systemd-sysext --help" "systemd-sysext" cmd_systemd_sysext --help
    run_t "systemd-creds list" "^" cmd_systemd_creds list
    run_t "systemd-creds show" "No credentials" cmd_systemd_creds show
    run_t "systemd-creds cat" "No credentials" cmd_systemd_creds cat
    run_t_exit_any "systemd-creds has-tpm2" "" cmd_systemd_creds has-tpm2
    run_t "systemd-creds --version" "systemd-creds OpenRC wrapper" cmd_systemd_creds --version
    run_t "systemd-creds --help" "systemd-creds" cmd_systemd_creds --help
    run_t "systemd-delta --version" "systemd-delta OpenRC wrapper" cmd_systemd_delta --version
    run_t "systemd-delta --help" "systemd-delta" cmd_systemd_delta --help
    run_t "systemd-delta exec" "overridden configuration files" cmd_systemd_delta
    run_t "systemd-firstboot --version" "systemd-firstboot OpenRC wrapper" cmd_systemd_firstboot --version
    run_t "systemd-firstboot --help" "systemd-firstboot" cmd_systemd_firstboot --help
    run_t "systemd-hwdb query" "completed" cmd_systemd_hwdb query
    run_t "systemd-hwdb --version" "systemd-hwdb OpenRC wrapper" cmd_systemd_hwdb --version
    run_t "systemd-hwdb --help" "systemd-hwdb" cmd_systemd_hwdb --help
    run_t "systemd-inhibit --list" "inhibitors listed" cmd_systemd_inhibit --list
    run_t "systemd-inhibit --version" "systemd-inhibit OpenRC wrapper" cmd_systemd_inhibit --version
    run_t "systemd-inhibit --help" "systemd-inhibit" cmd_systemd_inhibit --help
    run_t "systemd-machine-id-setup --version" "systemd-machine-id-setup OpenRC wrapper" cmd_systemd_machine_id_setup --version
    run_t "systemd-machine-id-setup --print" "[0-9a-f]{32}" cmd_systemd_machine_id_setup --print
    run_t "systemd-machine-id-setup --help" "systemd-machine-id-setup" cmd_systemd_machine_id_setup --help
    run_t "systemd-mount --list" "(NAME|MAJ:MIN|SIZE|TYPE|MOUNTPOINT|LABEL|UUID)" cmd_systemd_mount --list
    run_t "systemd-mount --version" "systemd-mount OpenRC wrapper" cmd_systemd_mount --version
    run_t "systemd-mount --help" "systemd-mount" cmd_systemd_mount --help
    run_t "systemd-notify --ready" "notification" cmd_systemd_notify --ready
    run_t "systemd-notify --version" "systemd-notify OpenRC wrapper" cmd_systemd_notify --version
    run_t "systemd-notify --help" "systemd-notify" cmd_systemd_notify --help
    run_t_exit_any "systemd-notify --booted" "" cmd_systemd_notify --booted
    run_t "systemd-run --version" "systemd-run OpenRC wrapper" cmd_systemd_run --version
    run_t "systemd-run --help" "systemd-run" cmd_systemd_run --help
    run_t "systemd-run exec" "Running as unit" cmd_systemd_run echo hello
    run_t "systemd-socket-activate --version" "systemd-socket-activate OpenRC wrapper" cmd_systemd_socket_activate --version
    run_t "systemd-socket-activate --help" "systemd-socket-activate" cmd_systemd_socket_activate --help
    run_t "systemd-stdio-bridge --version" "systemd-stdio-bridge OpenRC wrapper" cmd_systemd_stdio_bridge --version
    run_t "systemd-stdio-bridge --help" "systemd-stdio-bridge" cmd_systemd_stdio_bridge --help
    run_t "systemd-sysctl --cat-config" "cat-config" cmd_systemd_sysctl --cat-config
    run_t "systemd-sysctl --version" "systemd-sysctl OpenRC wrapper" cmd_systemd_sysctl --version
    run_t "systemd-sysctl --help" "systemd-sysctl" cmd_systemd_sysctl --help
    run_t "systemd-sysusers --cat-config" "" cmd_systemd_sysusers --cat-config
    run_t "systemd-sysusers --version" "systemd-sysusers OpenRC wrapper" cmd_systemd_sysusers --version
    run_t "systemd-sysusers --help" "systemd-sysusers" cmd_systemd_sysusers --help
    run_t "systemd-tmpfiles --cat-config" "cat-config" cmd_systemd_tmpfiles --cat-config
    run_t "systemd-tmpfiles --version" "systemd-tmpfiles OpenRC wrapper" cmd_systemd_tmpfiles --version
    run_t "systemd-tmpfiles --help" "systemd-tmpfiles" cmd_systemd_tmpfiles --help
    run_t "systemd-tty-ask-password-agent exec" "no password requests pending" cmd_systemd_tty_ask_password_agent
    run_t "systemd-tty-ask-password-agent --version" "systemd-tty-ask-password-agent OpenRC wrapper" cmd_systemd_tty_ask_password_agent --version
    run_t "systemd-tty-ask-password-agent --help" "systemd-tty-ask-password-agent" cmd_systemd_tty_ask_password_agent --help
    run_t "systemd-umount --version" "systemd-umount OpenRC wrapper" cmd_systemd_umount --version
    run_t "systemd-umount --help" "systemd-umount" cmd_systemd_umount --help
    run_t "systemd-vpick exec" "/etc" cmd_systemd_vpick /etc
    run_t "systemd-vpick --version" "systemd-vpick OpenRC wrapper" cmd_systemd_vpick --version
    run_t "systemd-vpick --help" "systemd-vpick" cmd_systemd_vpick --help

    if [ "$failed" -eq 0 ]; then
        return 0
    else
        return 1
    fi
}

get_default_dir_for_name() {
    case "$1" in
        systemd-sysctl|systemd-sysusers|systemd-tmpfiles|systemd-machine-id-setup|systemd-firstboot|systemd-hwdb)
            echo "/sbin"
            ;;
        *)
            echo "/bin"
            ;;
    esac
}

do_install() {
    check_root
    local force=0
    for a in "$@"; do [ "$a" = "--force" ] && force=1; done

    if ! el_dependencies_check "rc-service|rc-update|rc-status|openrc"; then
        el_error "OpenRC (>= $MIN_OPENRC_VERSION) does not appear to be installed. Aborting install."
        exit 1
    fi

    if [ -e "$MANIFEST_FILE" ]; then
        el_warning "An installation manifest already exists at $MANIFEST_FILE."
        el_warning "Re-running install will update links; run --uninstall first for a clean reinstall."
    fi

    mkdir -p "$MANIFEST_DIR" "$BACKUP_DIR" "$MASK_DIR"
    _TMP_MANIFEST="$MANIFEST_FILE.new"
    : > "$_TMP_MANIFEST"

    local target_real
    target_real=$(readlink -f "$WRAPPER_TARGET" 2>/dev/null || echo "$WRAPPER_TARGET")

    # Load existing manifest entries to avoid duplicates or lost history
    local -A existing_manifest_entries=()
    if [ -f "$MANIFEST_FILE" ]; then
        local m_line m_path
        while IFS= read -r m_line || [ -n "$m_line" ]; do
            [ -z "$m_line" ] && continue
            m_path=$(echo "$m_line" | cut -d'|' -f2)
            if [ -n "$m_path" ]; then
                existing_manifest_entries["$m_path"]="$m_line"
            fi
        done < "$MANIFEST_FILE"
    fi

    local -A processed_canon_paths=()
    local name dir path canon_path real_bin_found real_bin_path cur_target

    for name in "${NAMES[@]}"; do
        # Check if 'name' exists as a real binary (not our wrapper symlink) in any BINDIR
        real_bin_found=0
        real_bin_path=""
        for dir in "${BINDIRS[@]}"; do
            [ -d "$dir" ] || continue
            path="$dir/$name"
            if [ -e "$path" ] || [ -L "$path" ]; then
                cur_target=$(readlink -f "$path" 2>/dev/null || echo "")
                if [ "$cur_target" != "$target_real" ]; then
                    if [ ! -L "$path" ] || [ -e "$cur_target" ]; then
                        real_bin_found=1
                        real_bin_path="$path"
                        break
                    fi
                fi
            fi
        done

        if [ "$real_bin_found" -eq 1 ] && [ "$force" -ne 1 ]; then
            el_warning "skip $name (real binary present at $real_bin_path, provided by another tool; re-run with --install --force to overwrite)"
            continue
        fi

        # Find where 'name' currently exists or was previously recorded in manifest
        local target_paths=()
        for dir in "${BINDIRS[@]}"; do
            [ -d "$dir" ] || continue
            path="$dir/$name"
            if [ -e "$path" ] || [ -L "$path" ] || [ -n "${existing_manifest_entries["$path"]:-}" ]; then
                target_paths+=("$path")
            fi
        done

        # If 'name' is not present anywhere, use its default directory (/bin or /sbin)
        if [ ${#target_paths[@]} -eq 0 ]; then
            local default_dir
            default_dir=$(get_default_dir_for_name "$name")
            target_paths=("$default_dir/$name")
        fi

        for path in "${target_paths[@]}"; do
            canon_path=$(readlink -f "$path" 2>/dev/null || readlink -f "$(dirname "$path")"/$(basename "$path") 2>/dev/null || echo "$path")
            if [ -n "${processed_canon_paths["$canon_path"]:-}" ]; then
                continue
            fi
            processed_canon_paths["$canon_path"]=1

            if [ -L "$path" ]; then
                cur_target=$(readlink -f "$path" 2>/dev/null || echo "")
                if [ "$cur_target" = "$target_real" ]; then
                    el_debug "already linked: $path"
                    if [ -n "${existing_manifest_entries["$path"]:-}" ]; then
                        echo "${existing_manifest_entries["$path"]}" >> "$_TMP_MANIFEST"
                        unset 'existing_manifest_entries["$path"]'
                    fi
                    continue
                fi
                echo "symlink|$path|$(readlink "$path")" >> "$_TMP_MANIFEST"
                unset 'existing_manifest_entries["$path"]'
                rm -f "$path"
            elif [ -e "$path" ]; then
                local backup_path="$BACKUP_DIR$path"
                mkdir -p "$(dirname "$backup_path")"
                cp -a -- "$path" "$backup_path"
                echo "backup|$path|$backup_path" >> "$_TMP_MANIFEST"
                unset 'existing_manifest_entries["$path"]'
                rm -f "$path"
            else
                echo "created|$path|" >> "$_TMP_MANIFEST"
                unset 'existing_manifest_entries["$path"]'
            fi

            ln -sf "$WRAPPER_TARGET" "$path"
            el_info "linked: $path -> $WRAPPER_TARGET"
        done
    done

    # Preserve any remaining existing manifest entries for paths not processed
    local remaining_entry
    for remaining_entry in "${existing_manifest_entries[@]}"; do
        echo "$remaining_entry" >> "$_TMP_MANIFEST"
    done

    mv "$_TMP_MANIFEST" "$MANIFEST_FILE"
    _TMP_MANIFEST=""

    echo
    el_info "Installation complete."
    echo "  Manifest: $MANIFEST_FILE"
    echo "  Backups:  $BACKUP_DIR"
    echo "Run '$WRAPPER_TARGET --uninstall' any time to fully revert this."
    el_notify normal "system-run" "systemd-openrc-wrapper" "Installation complete. Systemd commands now run through OpenRC." 2>/dev/null
}

do_uninstall() {
    check_root
    local purge=0 assume_yes=0
    for a in "$@"; do
        [ "$a" = "--purge" ] && purge=1
        [ "$a" = "--yes" ] || [ "$a" = "-y" ] && assume_yes=1
    done

    if [ "$assume_yes" -ne 1 ]; then
        if ! el_confirm "This will remove the systemd-command symlinks and restore any original binaries. Continue?"; then
            el_info "Uninstall cancelled by user."
            exit 0
        fi
    fi

    local target_real; target_real=$(readlink -f "$WRAPPER_TARGET" 2>/dev/null)

    if [ ! -e "$MANIFEST_FILE" ]; then
        el_warning "No installation manifest found at $MANIFEST_FILE."
        el_warning "Nothing to restore automatically -- you may need to remove symlinks manually."
    else
        local type path extra
        while IFS='|' read -r type path extra; do
            [ -z "$type" ] && continue

            if [ -L "$path" ]; then
                local cur
                cur=$(readlink -f "$path" 2>/dev/null)
                if [ "$cur" != "$target_real" ]; then
                    el_warning "skip $path (symlink no longer points to the wrapper; leaving it alone)"
                    continue
                fi
                rm -f "$path"
            elif [ -e "$path" ]; then
                el_warning "skip $path (no longer a symlink; leaving it alone)"
                continue
            fi

            case "$type" in
                created)
                    el_debug "removed $path (originally created by installer, no prior binary existed)"
                    ;;
                symlink)
                    ln -sf "$extra" "$path"
                    el_info "restored original symlink: $path -> $extra"
                    ;;
                backup)
                    mkdir -p "$(dirname "$path")"
                    cp -a -- "$extra" "$path"
                    rm -f "$extra"
                    el_info "restored original binary: $path"
                    ;;
                *)
                    el_warning "unknown manifest entry type '$type' for $path -- skipped"
                    ;;
            esac
        done < "$MANIFEST_FILE"

        rm -f "$MANIFEST_FILE"
    fi

    rmdir --ignore-fail-on-non-empty "$BACKUP_DIR" 2>/dev/null
    rmdir --ignore-fail-on-non-empty "$MANIFEST_DIR" 2>/dev/null

    if [ "$purge" -eq 1 ]; then
        rm -rf "$MASK_DIR" "$MANIFEST_DIR"
        rm -f "$DEFAULT_RUNLEVEL_FILE"
        el_info "Purged mask database and leftover configuration."
    else
        [ -d "$MASK_DIR" ] && el_info "Mask database kept at $MASK_DIR (use --uninstall --purge to remove it too)."
    fi

    el_info "Uninstallation complete. System restored to its original (pre-wrapper) state."
    el_notify normal "system-run" "systemd-openrc-wrapper" "Uninstallation complete. System restored." 2>/dev/null
}

# ===========================================================================
# Help
# ===========================================================================
show_help() {
    local elive_ver; elive_ver=$(el_elive_version_get 2>/dev/null)
    cat <<EOF
systemd-openrc-wrapper v$VERSION
A compatibility shim that lets systemd-style commands run on OpenRC systems.
Minimum supported OpenRC version: $MIN_OPENRC_VERSION
(shipped as the default in Elive 3.8.60, built over Debian Trixie)
${elive_ver:+Detected Elive version: $elive_ver}

USAGE
  As the wrapper binary itself:
      systemd-openrc-wrapper <install|uninstall|check-install|help|version> [options]
      systemd-openrc-wrapper <systemctl|journalctl|...> <args...>

  Once installed, simply use the systemd commands as usual -- they are
  transparently translated to OpenRC equivalents:
      systemctl start nginx
      systemctl enable --now sshd
      journalctl -u cron -f
      hostnamectl set-hostname myhost

CORE WRAPPER COMMANDS
  install (or --install)
      sudo systemd-openrc-wrapper install
      sudo systemd-openrc-wrapper install --force

      Installs compatibility symlinks in system binary directories (/bin, /usr/bin,
      /sbin, /usr/sbin) pointing to systemd-openrc-wrapper for all supported systemd
      tools: systemctl, journalctl, hostnamectl, timedatectl, localectl, loginctl,
      systemd-ac-power, systemd-analyze, systemd-ask-password, systemd-cat, systemd-cgls,
      systemd-cgtop, systemd-confext, systemd-creds, systemd-delta, systemd-detect-virt,
      systemd-escape, systemd-firstboot, systemd-hwdb, systemd-id128, systemd-inhibit,
      systemd-machine-id-setup, systemd-mount, systemd-notify, systemd-path, systemd-run,
      systemd-socket-activate, systemd-stdio-bridge, systemd-sysext, systemd-sysctl,
      systemd-sysusers, systemd-tmpfiles, systemd-tty-ask-password-agent, systemd-umount,
      and systemd-vpick.

      - Manifest: Records every modified path in $MANIFEST_FILE.
      - Safety Backups: Any pre-existing binaries replaced are safely backed up to
        $BACKUP_DIR.
      - Skips existing real binaries from other packages by default unless --force
        is provided.

  uninstall (or --uninstall)
      sudo systemd-openrc-wrapper uninstall
      sudo systemd-openrc-wrapper uninstall --yes
      sudo systemd-openrc-wrapper uninstall --purge

      Restores the system to EXACTLY its state prior to installation:
      - Removes all wrapper symlinks created during installation.
      - Restores original binary files from $BACKUP_DIR.
      - Restores pre-existing symlinks that pointed elsewhere prior to install.
      - Flags:
          --yes, -y    Skip the interactive confirmation prompt.
          --purge      Also remove mask database ($MASK_DIR) and wrapper configuration files.

  check-install (or --check-install)
      systemd-openrc-wrapper check-install

      Inspects all system binary paths (/bin, /usr/bin, /sbin, /usr/sbin) for systemd
      command names. Reports whether each command is installed, if it points to the
      wrapper, and its associated dpkg package ownership (verifying if commands belong
      to systemd packages or external tools).

  test (or --test, check-compat)
      systemd-openrc-wrapper test

      Runs compatibility test suite verifying that systemd commands translate properly
      under OpenRC on the current system, outputting OK/FAILED status for each command.

  help (or --help, -h)
      systemd-openrc-wrapper help

      Prints this full usage documentation and list of translated systemd commands.

  version (or --version, -v)
      systemd-openrc-wrapper version

      Prints wrapper version and minimum supported OpenRC version.

  Storage Locations:
      Manifest: $MANIFEST_FILE
      Backups:  $BACKUP_DIR

EXAMPLES
  # Service management
  systemctl start docker
  systemctl stop docker
  systemctl restart docker
  systemctl reload nginx
  systemctl status sshd
  systemctl enable --now cronie
  systemctl disable cronie
  systemctl is-active sshd
  systemctl is-enabled sshd
  systemctl mask bluetooth
  systemctl unmask bluetooth
  systemctl list-units
  systemctl list-units --state=started
  systemctl list-unit-files
  systemctl get-default
  systemctl isolate rescue.target
  systemctl --user start my-agent.service

  # Logs
  journalctl -u nginx -f
  journalctl -n 200
  journalctl -k              # dmesg
  journalctl --disk-usage
  journalctl --list-boots

  # Host/locale/time
  hostnamectl set-hostname myhost
  timedatectl set-timezone Europe/Madrid
  timedatectl set-time "2024-01-01 12:00:00"
  localectl set-keymap es

  # Misc
  systemd-run sleep 60
  systemd-cat -t mytag echo "hello"
  systemd-tmpfiles --create
  systemd-sysctl

ENVIRONMENT VARIABLES
  SYSTEMD_OPENRC_WRAPPER_QUIET=1   Suppress the "this is OpenRC, we
                                   translated your command to X" notices.
  SYSTEMD_OPENRC_WRAPPER_DEBUG=1   Print extra debug information.

MESSAGE SEVERITY
  el_info / [INFO]     Successful translation of a systemd call to OpenRC.
  el_warning / [WARN]  The feature only works partially (half-emulated).
  el_error / [ERROR]   The feature is not implemented -- it will not work.

NOTES / LIMITATIONS
  - Requires OpenRC >= $MIN_OPENRC_VERSION. No fallbacks are provided for
    older releases (e.g. this relies on 'rc-service --user',
    'rc-update --user' and 'rc-status --in-state', all guaranteed
    present since OpenRC 0.60/0.62).
  - This is best-effort translation, not a reimplementation of systemd.
  - systemd timers, socket activation, cgroup resource limits via unit
    files, and the full binary journal format have no direct OpenRC
    equivalent and are not emulated (el_error where applicable).
  - 'mask'/'unmask' are emulated using marker files under:
      $MASK_DIR
    since OpenRC has no native masking concept.
  - Root-requiring actions automatically elevate via el_sudo instead of
    failing outright.
  - Every translated invocation prints an informational note to stderr
    (disable with SYSTEMD_OPENRC_WRAPPER_QUIET=1) suggesting the native
    OpenRC command you could use directly instead.
EOF
}

# ===========================================================================
# Dispatcher
# ===========================================================================
dispatch_by_name() {
    case "$1" in
        systemctl)                    shift; cmd_systemctl "$@" ;;
        journalctl)                   shift; cmd_journalctl "$@" ;;
        hostnamectl)                  shift; cmd_hostnamectl "$@" ;;
        timedatectl)                  shift; cmd_timedatectl "$@" ;;
        localectl)                    shift; cmd_localectl "$@" ;;
        loginctl)                     shift; cmd_loginctl "$@" ;;
        systemd-ac-power)             shift; cmd_systemd_ac_power "$@" ;;
        systemd-analyze)              shift; cmd_systemd_analyze "$@" ;;
        systemd-ask-password)         shift; cmd_systemd_ask_password "$@" ;;
        systemd-cat)                  shift; cmd_systemd_cat "$@" ;;
        systemd-cgls)                 shift; cmd_systemd_cgls "$@" ;;
        systemd-cgtop)                shift; cmd_systemd_cgtop "$@" ;;
        systemd-confext)              shift; cmd_systemd_confext "$@" ;;
        systemd-creds)                shift; cmd_systemd_creds "$@" ;;
        systemd-delta)                shift; cmd_systemd_delta "$@" ;;
        systemd-detect-virt)          shift; cmd_systemd_detect_virt "$@" ;;
        systemd-escape)               shift; cmd_systemd_escape "$@" ;;
        systemd-firstboot)            shift; cmd_systemd_firstboot "$@" ;;
        systemd-hwdb)                 shift; cmd_systemd_hwdb "$@" ;;
        systemd-id128)                shift; cmd_systemd_id128 "$@" ;;
        systemd-inhibit)              shift; cmd_systemd_inhibit "$@" ;;
        systemd-machine-id-setup)     shift; cmd_systemd_machine_id_setup "$@" ;;
        systemd-mount)                shift; cmd_systemd_mount "$@" ;;
        systemd-notify)               shift; cmd_systemd_notify "$@" ;;
        systemd-path)                 shift; cmd_systemd_path "$@" ;;
        systemd-run)                  shift; cmd_systemd_run "$@" ;;
        systemd-socket-activate)      shift; cmd_systemd_socket_activate "$@" ;;
        systemd-stdio-bridge)         shift; cmd_systemd_stdio_bridge "$@" ;;
        systemd-sysext)               shift; cmd_systemd_sysext "$@" ;;
        systemd-sysctl)               shift; cmd_systemd_sysctl "$@" ;;
        systemd-sysusers)             shift; cmd_systemd_sysusers "$@" ;;
        systemd-tmpfiles)             shift; cmd_systemd_tmpfiles "$@" ;;
        systemd-tty-ask-password-agent) shift; cmd_systemd_tty_ask_password_agent "$@" ;;
        systemd-umount)               shift; cmd_systemd_umount "$@" ;;
        systemd-vpick)                shift; cmd_systemd_vpick "$@" ;;
        *) return 1 ;;
    esac
    return 0
}

case "$SCRIPT_NAME" in
    systemctl|journalctl|hostnamectl|timedatectl|localectl|loginctl|\
    systemd-ac-power|systemd-analyze|systemd-ask-password|systemd-cat|\
    systemd-cgls|systemd-cgtop|systemd-confext|systemd-creds|systemd-delta|\
    systemd-detect-virt|systemd-escape|systemd-firstboot|systemd-hwdb|\
    systemd-id128|systemd-inhibit|systemd-machine-id-setup|systemd-mount|\
    systemd-notify|systemd-path|systemd-run|systemd-socket-activate|\
    systemd-stdio-bridge|systemd-sysext|systemd-sysctl|systemd-sysusers|\
    systemd-tmpfiles|systemd-tty-ask-password-agent|systemd-umount|systemd-vpick)
        dispatch_by_name "$SCRIPT_NAME" "$@"
        ;;
    *)
        case "$1" in
            --install|install)           shift; do_install "$@" ;;
            --uninstall|uninstall)       shift; do_uninstall "$@" ;;
            --check-install|check-install) shift; do_check_install "$@" ;;
            --test|test|--test-compat|test-compat|--check-compat|check-compat) shift; do_test_compat "$@" ;;
            --version|version|-v)
                echo "systemd-openrc-wrapper v$VERSION (requires OpenRC >= $MIN_OPENRC_VERSION)"
                el_elive_version_get 2>/dev/null
                ;;
            --help|-h|help|"")     show_help ;;
            *)
                if ! dispatch_by_name "$@"; then
                    el_error "unknown command or mode: $1 (see --help)"
                    exit 1
                fi
                ;;
        esac
        ;;
esac
