#!/bin/bash
# hydrogen-workspace: the subset of the wsl.exe command line Adom Hydrogen uses, on a Linux host,
# backed by systemd-nspawn / machinectl instead of WSL2.
#
# Hydrogen (unprivileged) runs this as `sudo -n /usr/libexec/adom-hydrogen/hydrogen-workspace <wsl args>`.
# The sudoers drop-in allows exactly this one root-owned file. It manages ONE machine,
# Adom-Workspace, and refuses every other name, so it can never touch another container.
#
#   --status | --version                 runtime present? (machinectl + systemd-nspawn)
#   -l -q | -l -v | -l --running -q      list the workspace machine, WSL output format
#   --import NAME DIR TAR [--version 2]  machinectl import-tar TAR NAME (+ settings file)
#   --export NAME FILE                   machinectl export-tar
#   --terminate NAME                     stop the machine (waits until it is gone)
#   --shutdown                           ONLY our machine; never anything global
#   --unregister NAME                    terminate + remove the image
#   -d NAME [-u USER] [-e|--exec|--] CMD...
#                                        run CMD inside the machine as USER (default adom),
#                                        booting it first if needed (WSL auto-starts a distro
#                                        on exec the same way)
#   --helper-version                     prints HELPER_VERSION (Hydrogen re-installs on skew)
set -u
HELPER_VERSION=14
M=Adom-Workspace
POOL=/var/lib/machines
SETTINGS=/etc/systemd/nspawn/$M.nspawn

die() { echo "hydrogen-workspace: $*" >&2; exit 1; }
[ "$(id -u)" = 0 ] || die "must run as root (sudo -n)"
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

check_name() { [ "${1:-}" = "$M" ] || die "refusing machine '${1:-}' (only $M is managed here)"; }
have_runtime() { command -v machinectl >/dev/null 2>&1 && command -v systemd-nspawn >/dev/null 2>&1; }
leader() { machinectl show "$M" -p Leader --value 2>/dev/null; }
running() { local l; l=$(leader); [ -n "$l" ] && [ "$l" != 0 ] && [ -d "/proc/$l" ]; }
# Booted far enough to exec into: the leader is systemd (not the pre-exec nspawn child).
ready() { local l; l=$(leader); running && [ "$(basename "$(readlink "/proc/$l/exe" 2>/dev/null)")" = systemd ] && [ -S "/proc/$l/root/run/systemd/private" ]; }
image_present() { [ -d "$POOL/$M" ] || [ -f "$POOL/$M.raw" ]; }

write_settings() {
    # Host network (no veth): 127.0.0.1 is shared with the host, the Linux equivalent of
    # WSL2 mirrored networking. PrivateUsers=no keeps uids literal (adom = 1001), so the
    # import does not have to chown 2+ GB. /mnt/host carries the host paths Hydrogen hands
    # the workspace (the WSL /mnt/c equivalent).
    mkdir -p /etc/systemd/nspawn
    cat > "$SETTINGS" <<EOF
# Written by Adom Hydrogen (hydrogen-workspace $HELPER_VERSION). Edits are overwritten.
[Exec]
Boot=yes
PrivateUsers=no
LinkJournal=no
ResolvConf=bind-stub

[Files]
TemporaryFileSystem=/tmp:mode=1777,size=25%
Bind=/home:/mnt/host/home
Bind=/tmp:/mnt/host/tmp
BindReadOnly=/usr:/mnt/host/usr
BindReadOnly=/opt:/mnt/host/opt

[Network]
Private=no
VirtualEthernet=no
EOF
}

wait_gone() {
    local i
    for i in $(seq 1 "${1:-40}"); do running || return 0; sleep 0.25; done
    return 1
}

stop_machine() {
    running || { systemctl reset-failed "systemd-nspawn@$M.service" >/dev/null 2>&1; return 0; }
    machinectl poweroff "$M" >/dev/null 2>&1
    wait_gone 40 && return 0
    machinectl terminate "$M" >/dev/null 2>&1
    wait_gone 40 && return 0
    systemctl kill -s KILL "systemd-nspawn@$M.service" >/dev/null 2>&1
    wait_gone 40
    systemctl reset-failed "systemd-nspawn@$M.service" >/dev/null 2>&1
    running && return 1
    return 0
}

# Keep the workspace off the LAN. The machine shares the host network, so anything in it that
# listens on 0.0.0.0 (the relay on 8765/8766, adom-shotlog on 8820, a dev server the user
# starts) would be reachable from other computers; on Windows the Hyper-V firewall blocks that
# for mirrored ports. One table of our own: loopback and replies to the workspace's own
# connections pass, NEW inbound connections to the workspace ports, or to any listener inside
# machine.slice, are dropped. Re-applied on every machine start (it does not persist a reboot).
PROTECT_PORTS="7380, 8765, 8766, 8820, 8821"
# Codex's and Claude Code's shell sandbox is bubblewrap, which needs a user namespace. Ubuntu
# 23.10+ sets kernel.apparmor_restrict_unprivileged_userns=1: an unconfined process may create
# one, but is moved into `unprivileged_userns`, which strips every capability, so bwrap cannot
# write uid_map or bring up loopback ("Codex's Linux sandbox uses bubblewrap and needs access to
# create user namespaces"; the same on the bare host, not an nspawn limit). This loads Ubuntu's
# own opt-in design (bwrap-userns-restrict): bwrap may set the namespace up, and everything it
# starts is stacked under adom_unpriv_bwrap, which denies every capability and nested userns, so
# a sandboxed command gains nothing. AppArmor matches the path as the workspace sees it, so it
# covers the workspace's /usr/bin/bwrap and Codex's bundled copies (and the host's bwrap).
# Hosts without the restriction (Debian, Fedora, WSL) are left alone. Kept in /etc/apparmor.d so
# it survives a reboot; prerm removes it.
BWRAP_PROFILE=/etc/apparmor.d/adom-hydrogen-bwrap
allow_bwrap_userns() {
    [ "$(cat /proc/sys/kernel/apparmor_restrict_unprivileged_userns 2>/dev/null)" = 1 ] || return 0
    command -v apparmor_parser >/dev/null 2>&1 || return 0
    local want; want=$(cat <<'AA'
# Written by Adom Hydrogen (hydrogen-workspace). Edits are overwritten; removed on uninstall.
abi <abi/4.0>,
include <tunables/global>

profile adom_bwrap /{usr/bin/bwrap,bin/bwrap,home/*/.local/share/{code-server/extensions/openai.chatgpt-*,adom/codex-engine/*}/**/codex-resources/bwrap} flags=(attach_disconnected,mediate_deleted) {
  allow capability,
  allow file rwlkm /{**,},
  allow unix,
  allow dbus,
  allow network,
  allow mount,
  allow umount,
  allow remount,
  allow pivot_root,
  allow userns,
  allow signal,
  allow mqueue,
  allow ptrace,
  allow pix /** -> &adom_bwrap//&adom_unpriv_bwrap,
}

profile adom_unpriv_bwrap flags=(attach_disconnected,mediate_deleted) {
  allow file rwlkm /{**,},
  allow unix,
  allow dbus,
  allow network,
  allow mount,
  allow umount,
  allow remount,
  allow pivot_root,
  allow signal,
  allow mqueue,
  allow ptrace,
  allow pix /** -> &adom_unpriv_bwrap,
  audit deny capability,
  audit deny userns,
}
AA
)
    if [ "$(cat "$BWRAP_PROFILE" 2>/dev/null)" = "$want" ] \
       && grep -q '^adom_bwrap ' /sys/kernel/security/apparmor/profiles 2>/dev/null; then
        return 0
    fi
    mkdir -p /etc/apparmor.d
    printf '%s\n' "$want" > "$BWRAP_PROFILE"
    apparmor_parser -r "$BWRAP_PROFILE" >/dev/null 2>&1 || echo "hydrogen-workspace: could not load $BWRAP_PROFILE (Codex's sandbox stays off)" >&2
    return 0
}

protect_lan() {
    if command -v nft >/dev/null 2>&1; then
        nft delete table inet adom_hydrogen >/dev/null 2>&1
        # The cgroup match needs machine.slice to exist (it does once a machine runs) and a
        # kernel/nft with socket cgroupv2; fall back to the port list alone.
        local extra
        for extra in 'socket cgroupv2 level 1 "machine.slice" ct state new drop' ''; do
            nft -f - >/dev/null 2>&1 <<NFT && break
table inet adom_hydrogen {
    chain input {
        type filter hook input priority -5; policy accept;
        iifname "lo" accept
        ct state established,related accept
        tcp dport { $PROTECT_PORTS } drop
        $extra
    }
}
NFT
            nft delete table inet adom_hydrogen >/dev/null 2>&1
        done
    elif command -v iptables >/dev/null 2>&1; then
        # No nft tool (a host without the nftables package): the known ports for IPv4 AND IPv6
        # (nft's inet table covers both). This cannot drop everything the workspace serves (the
        # iptables cgroup match does not see a listening socket; tried on hl-debian 2026-11-06),
        # so the packages depend on nftables and the AppImage's host prep installs it.
        local ipt
        for ipt in iptables ip6tables; do
            command -v "$ipt" >/dev/null 2>&1 || continue
            "$ipt" -N ADOM_HYDROGEN >/dev/null 2>&1; "$ipt" -F ADOM_HYDROGEN
            "$ipt" -A ADOM_HYDROGEN -i lo -j RETURN
            "$ipt" -A ADOM_HYDROGEN -m conntrack --ctstate ESTABLISHED,RELATED -j RETURN
            "$ipt" -A ADOM_HYDROGEN -p tcp -m multiport --dports "${PROTECT_PORTS// /}" -j DROP
            "$ipt" -C INPUT -j ADOM_HYDROGEN >/dev/null 2>&1 || "$ipt" -I INPUT -j ADOM_HYDROGEN
        done
    fi
    return 0
}

# VS Code webviews under WebKitGTK (Claude Code's panel stayed blank): WebKit's clients.matchAll()
# in the webview service worker returns [] and SW->client messages never arrive, so every webview
# resource 404s. Patch the service worker (inside the machine, as root, with its python3) to load
# such resources straight from code-server. Idempotent; re-applied each start so a code-server
# update is re-patched. A changed file shape is reported, never forced.
patch_webviews() {
    local l=$1 d
    d=$(nsenter -t "$l" -a sh -c 'ls -d /usr/lib/code-server/lib/vscode/out/vs/workbench/contrib/webview/browser/pre 2>/dev/null' | head -1)
    [ -n "$d" ] || return 0
    nsenter -t "$l" -a python3 - "$d" >/dev/null 2>/tmp/hydrogen-workspace-swfix.err <<'PYFIX' || echo "hydrogen-workspace: webview fix not applied: $(tail -1 /tmp/hydrogen-workspace-swfix.err)" >&2
# Hydrogen Linux fix: VS Code webviews under WebKitGTK. In the webview service worker WebKit's
# clients.matchAll() returns [] and SW->client messages never arrive, so the SW can never ask
# the workbench for a webview resource and every load is a 404 (Claude Code's panel stays blank).
# When no parent frame is found, fetch the resource straight from code-server's
# /vscode-remote-resource route (same origin as the webview frames, which could already fetch
# it themselves, so nothing new is exposed). Idempotent: marker HYDROGEN-SWFIX2.
import os, sys
d = sys.argv[1]  # .../vs/workbench/contrib/webview/browser/pre
sw = os.path.join(d, 'service-worker.js')
s = open(sw).read()
if 'HYDROGEN-SWFIX2' in s:
    print('HYDROGEN-SWFIX2 already applied'); sys.exit(0)
old = """		const parentClients = await getOuterIframeClient(webviewId);
		if (!parentClients.length) {
			console.log('Could not find parent client for request');
			return notFound();
		}

		for (const parentClient of parentClients) {
			parentClient.postMessage({
				channel: 'load-resource',"""
new = """		const parentClients = await getOuterIframeClient(webviewId);
		if (!parentClients.length) {
			// HYDROGEN-SWFIX2: WebKit finds no parent client; load from code-server directly.
			if (requestUrlComponents.scheme === 'vscode-remote' || requestUrlComponents.scheme === 'file') {
				try {
					const base = sw.location.pathname.split('/static/')[0];
					const u = new URL(base + '/vscode-remote-resource', sw.location.origin);
					u.searchParams.set('path', decodeURIComponent(requestUrlComponents.path));
					const headers = {};
					const range = event.request.headers.get('range');
					if (range) { headers['range'] = range; }
					const r = await fetch(u.toString(), { headers, credentials: 'same-origin' });
					if (r.status !== 200 && r.status !== 206) { return notFound(); }
					const h = new Headers(r.headers);
					h.set('Access-Control-Allow-Origin', '*');
					h.set('Cross-Origin-Resource-Policy', 'cross-origin');
					return new Response(r.body, { status: r.status, headers: h });
				} catch (e) {
					console.log('HYDROGEN-SWFIX2 direct load failed', e);
				}
			}
			console.log('Could not find parent client for request');
			return notFound();
		}

		for (const parentClient of parentClients) {
			parentClient.postMessage({
				channel: 'load-resource',"""
assert old in s, 'service-worker.js shape changed; fix not applied'
s = s.replace(old, new, 1)
open(sw, 'w').write(s)
print('HYDROGEN-SWFIX2 applied')
PYFIX
}

# Editor links to localhost lost their path (Ralph F44): code-server's resolveExternalUri replaces
# http://127.0.0.1:47084/buildinfo with the rendered proxy template (http://47084.localhost:47083/)
# and drops the path, query and fragment. Patch the workbench (inside the machine, as root) so the
# original path/query/fragment ride along after the template's own path. Idempotent (marker
# HYDROGEN-EXTPATH), re-applied each start; an unknown file shape is reported, never forced.
patch_external_links() {
    local l=$1
    nsenter -t "$l" -a python3 - >/dev/null 2>/tmp/hydrogen-workspace-extpath.err <<'PYEXT' || echo "hydrogen-workspace: link path fix not applied: $(tail -1 /tmp/hydrogen-workspace-extpath.err)" >&2
import os, re, sys
base = '/usr/lib/code-server/lib/vscode/out/vs'
files = [os.path.join(base, 'code/browser/workbench/workbench.js'),
         os.path.join(base, 'workbench/workbench.web.main.internal.js')]
pat = re.compile(r'(\.replace\("\{\{host\}\}",window\.location\.host\);)([\w$]+)=([\w$]+)\.parse\(new URL\(([\w$]+),window\.location\.href\)\.toString\(\)\)')
done = 0
for f in files:
    if not os.path.exists(f):
        continue
    s = open(f).read()
    if 'HYDROGEN-EXTPATH' in s:
        done += 1; continue
    def rep(m):
        pre, r, N, l = m.groups()
        return (pre + r + '=(function(o,u){/*HYDROGEN-EXTPATH*/return u.with({path:(u.path.replace(/\\/$/,"")+o.path)||"/",query:o.query,fragment:o.fragment})})(' + r + ',' + N + '.parse(new URL(' + l + ',window.location.href).toString()))')
    s2, n = pat.subn(rep, s, count=1)
    if n:
        open(f, 'w').write(s2); done += 1
if not done:
    sys.exit('resolveExternalUri shape changed; link path fix not applied')
print('HYDROGEN-EXTPATH applied to', done, 'file(s)')
PYEXT
}

# The workspace carries the host's name, as a WSL distro carries the PC's: the golden image's
# /etc/hostname said "AdomLapper" (the box it was built on), so Claude in the workspace told John
# Hydrogen was "running on AdomLapper" (hl-ubuntu, 2026-11-03). Written into the image before
# boot (the container's systemd sets the name from /etc/hostname), with a 127.0.1.1 line in
# /etc/hosts so the name resolves, and set live on a running machine whose name differs.
host_name() {
    local h; h=$(hostname -s 2>/dev/null || hostname)
    [[ "$h" =~ ^[A-Za-z0-9][A-Za-z0-9-]{0,62}$ ]] && echo "$h"
}
sync_hostname() { # [leader]
    local h root=$POOL/$M; h=$(host_name) || return 0
    [ -n "$h" ] || return 0
    if [ -d "$root/etc" ]; then
        [ "$(cat "$root/etc/hostname" 2>/dev/null)" = "$h" ] || printf '%s\n' "$h" > "$root/etc/hostname"
        if [ -f "$root/etc/hosts" ] && ! grep -qE "^127\.0\.1\.1[[:space:]]+$h([[:space:]]|\$)" "$root/etc/hosts"; then
            sed -i '/^127\.0\.1\.1[[:space:]]/d' "$root/etc/hosts"
            printf '127.0.1.1\t%s\n' "$h" >> "$root/etc/hosts"
        fi
    fi
    if [ -n "${1:-}" ] && [ "$(nsenter -t "$1" -u hostname 2>/dev/null)" != "$h" ]; then
        nsenter -t "$1" -u hostname "$h" >/dev/null 2>&1
    fi
    return 0
}

# The golden image is made by booting it on the build machine (AdomLapper), and its persistent
# journal kept that build boot: a fresh workspace's journal (and so the boot log setup shows)
# carried "AdomLapper" lines that were never this computer's (Ralph batch 31, 2026-11-06). Drop
# the image's own journal files on import; this machine's boots then start a clean journal under
# this computer's name (sync_hostname runs before every boot).
clear_image_journal() {
    local j=$POOL/$M/var/log/journal
    [ -d "$j" ] && [ ! -L "$j" ] && find "$j" -mindepth 1 -xdev -delete 2>/dev/null
    return 0
}

# Every workspace gets its own machine ID (DIR-061217-14703). The image ships one
# /etc/machine-id, so every install had the same one (the journal, D-Bus and anything that keys
# identity on it). Written before the machine boots: at import, and once on an install made
# before helper 11 (the marker says it was done). /var/lib/dbus/machine-id follows /etc.
unique_machine_id() {
    local root=$POOL/$M mark=$POOL/$M/var/lib/adom/machine-id-unique id
    [ -d "$root/etc" ] || return 0
    [ -f "$mark" ] && return 0
    id=$(tr -d '-' < /proc/sys/kernel/random/uuid)
    [ ${#id} = 32 ] || return 0
    printf '%s\n' "$id" > "$root/etc/.machine-id.new" && chmod 0444 "$root/etc/.machine-id.new" \
        && mv -f "$root/etc/.machine-id.new" "$root/etc/machine-id" || return 0
    if [ -d "$root/var/lib/dbus" ]; then
        ln -sfn /etc/machine-id "$root/var/lib/dbus/machine-id"
    fi
    mkdir -p "$root/var/lib/adom" && printf '%s\n' "$id" > "$mark"
    return 0
}

start_machine() {
    ready && return 0
    image_present || die "There is no distribution with the supplied name. ($M is not imported)"
    [ -f "$SETTINGS" ] || write_settings
    unique_machine_id
    sync_hostname
    systemctl reset-failed "systemd-nspawn@$M.service" >/dev/null 2>&1
    machinectl start "$M" >/dev/null 2>&1 || systemctl start "systemd-nspawn@$M.service" || die "machinectl start $M failed"
    local i l
    for i in $(seq 1 120); do
        l=$(leader)
        # The leader is registered while it is still the nspawn child, BEFORE it execs
        # systemd (its cmdline is then systemd-nspawn and the mount tree is not final).
        # Entering it in that window ran commands half outside the machine (seen 2026-11-01).
        # Wait until the leader IS systemd and its private bus socket exists.
        if [ -n "$l" ] && [ "$l" != 0 ] \
           && [ "$(basename "$(readlink "/proc/$l/exe" 2>/dev/null)")" = systemd ] \
           && [ -S "/proc/$l/root/run/systemd/private" ]; then
            # Give PID 1 a bounded chance to finish booting so a first `systemctl start`
            # inside does not race the boot transaction (WSL has the same behaviour).
            nsenter -t "$l" -a timeout 30 systemctl is-system-running --wait >/dev/null 2>&1
            protect_lan
            allow_bwrap_userns
            sync_hostname "$l"
            patch_webviews "$l"; patch_external_links "$l"
            return 0
        fi
        sleep 0.25
    done
    die "$M did not boot within 30 s"
}

# Unpack the golden rootfs into the machine pool ourselves. `machinectl import-tar` is not
# portable: systemd 259 (Fedora 44) redirects it to importctl, whose systemd-importd died with
# "Transport endpoint is not connected" on every attempt (hl-fedora 2026-11-02). tar as root
# keeps owners numeric (adom = 1001) and file capabilities. On a btrfs pool the machine is a
# subvolume, which is what importd would have made.
import_tar() {
    local tar=$1 tmp="$POOL/.$M.importing"
    mkdir -p "$POOL"; chmod 0700 "$POOL"
    remove_tree "$tmp"
    if [ "$(stat -f -c %T "$POOL" 2>/dev/null)" = btrfs ] && command -v btrfs >/dev/null 2>&1; then
        btrfs -q subvolume create "$tmp" >/dev/null || mkdir "$tmp"
    else
        mkdir "$tmp"
    fi
    if ! tar --numeric-owner --xattrs --xattrs-include='*' -xpzf "$tar" -C "$tmp" 2>/tmp/hydrogen-workspace-tar.err; then
        tail -3 /tmp/hydrogen-workspace-tar.err >&2; remove_tree "$tmp"; return 1
    fi
    mv "$tmp" "$POOL/$M"
    # SELinux hosts: give the tree the pool's default labels (nspawn runs unconfined by default).
    if command -v selinuxenabled >/dev/null 2>&1 && selinuxenabled && command -v restorecon >/dev/null 2>&1; then
        restorecon -R "$POOL/$M" >/dev/null 2>&1 || true
    fi
    image_present
}

remove_tree() {
    [ -e "$1" ] || return 0
    if [ "$(stat -f -c %T "$1" 2>/dev/null)" = btrfs ] && btrfs subvolume show "$1" >/dev/null 2>&1; then
        btrfs -q subvolume delete "$1" >/dev/null 2>&1 && return 0
    fi
    rm -rf --one-file-system "$1"
}

list() { # $1 = q|v|runq
    case "$1" in
        q)    image_present && echo "$M" ;;
        runq) running && echo "$M" ;;
        v)
            echo "  NAME              STATE           VERSION"
            if image_present; then
                if running; then st=Running; else st=Stopped; fi
                printf "* %-17s %-15s %s\n" "$M" "$st" 2
            fi ;;
    esac
    return 0
}

# DIR-061347-30980: nsenter joins the machine's namespaces but not its cgroup, so a process
# started through this helper stayed in the caller's cgroup (user.slice) and the nftables rule
# that drops new outside connections to anything in machine.slice missed it (a server started
# this way on 0.0.0.0 was reachable from the LAN, hl-debian 2026-11-06). Join a leaf cgroup
# inside the machine's own tree first, beside the machine's init.scope:
#   /machine.slice/systemd-nspawn@Adom-Workspace.service/payload/hydrogen-exec
# $$ is this shell, which `exec nsenter` keeps, so everything it starts inherits the cgroup.
# Stopping the machine stops these processes too. Best effort: no cgroup v2, no change.
join_machine_cgroup() {
    local l=$1 cg base
    cg=$(sed -n 's/^0:://p' "/proc/$l/cgroup" 2>/dev/null)
    case "$cg" in /machine.slice/*) ;; *) return 0 ;; esac
    base=/sys/fs/cgroup${cg%/*}
    [ -d "$base" ] || return 0
    mkdir -p "$base/hydrogen-exec" 2>/dev/null || return 0
    echo $$ > "$base/hydrogen-exec/cgroup.procs" 2>/dev/null || true
    return 0
}

exec_in() { # user cmd...
    local user=$1; shift
    [ $# -gt 0 ] || set -- bash -l
    # wslinfo exists only inside WSL; answer the one question Hydrogen asks.
    if [ "$1" = wslinfo ]; then echo mirrored; return 0; fi
    start_machine
    local l; l=$(leader)
    local root=/proc/$l/root
    local ent; ent=$(awk -F: -v u="$user" '$1==u{print $3":"$4":"$6; exit}' "$root/etc/passwd")
    [ -n "$ent" ] || die "user '$user' does not exist in $M"
    local uid=${ent%%:*}; local rest=${ent#*:}; local gid=${rest%%:*}; local home=${rest#*:}
    local ids=()
    [ "$uid" != 0 ] && ids=(-S "$uid" -G "$gid")
    local path=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    [ "$uid" != 0 ] && path="$home/.local/bin:$home/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin"
    join_machine_cgroup "$l"
    exec nsenter -t "$l" -a "${ids[@]}" -- /usr/bin/env -i \
        HOME="$home" USER="$user" LOGNAME="$user" SHELL=/bin/bash PATH="$path" \
        TERM="${TERM:-xterm-256color}" LANG=C.UTF-8 LC_ALL=C.UTF-8 \
        HYDROGEN_HOST=linux WSL_DISTRO_NAME="$M" \
        /bin/sh -c 'cd "$HOME" 2>/dev/null || cd /; exec "$@"' sh "$@"
}

[ $# -gt 0 ] || die "no arguments"
case "$1" in
    --helper-version) echo "$HELPER_VERSION"; exit 0 ;;
    --listeners)
        # Ralph F95: "<port> <pid> <cgroup>" for every listening TCP socket. Hydrogen runs as the
        # desktop user and cannot read the fds of root's (sshd, cupsd, systemd-resolved) or the
        # workspace's processes, so the Ports dialog could not tell this computer's own services
        # from the workspace's and listed them all as inside it. Read-only.
        command -v ss >/dev/null 2>&1 || exit 0
        ss -Hltnp 2>/dev/null | while read -r _st _rq _sq local _peer users; do
            port=${local##*:}
            for pid in $(printf '%s' "$users" | grep -o 'pid=[0-9]*' | cut -d= -f2 | sort -u); do
                printf '%s %s %s\n' "$port" "$pid" "$(sed -n 's/^0:://p' "/proc/$pid/cgroup" 2>/dev/null)"
            done
        done
        exit 0 ;;
    --status)
        have_runtime || die "systemd-container (machinectl, systemd-nspawn) is not installed"
        if running; then protect_lan; allow_bwrap_userns; sync_hostname "$(leader)"; patch_webviews "$(leader)"; patch_external_links "$(leader)"; fi
        echo "Default Version: 2"
        echo "Runtime: systemd-nspawn on $(uname -sr) (Adom Hydrogen Linux host)"
        exit 0 ;;
    --version)
        have_runtime || die "systemd-container is not installed"
        echo "WSL version: 2.0.0-nspawn"
        echo "Kernel version: $(uname -r)"
        echo "systemd: $(systemctl --version | head -1)"
        exit 0 ;;
    -l|--list)
        shift
        mode=v
        for a in "$@"; do
            case "$a" in -q|--quiet) [ "$mode" = runq ] || mode=q ;; --running) mode=runq ;; -v|--verbose) mode=v ;; esac
        done
        list "$mode"; exit 0 ;;
    --import)
        check_name "${2:-}"
        tar=${4:-}; [ -f "$tar" ] || die "tarball not found: $tar"
        have_runtime || die "systemd-container is not installed"
        image_present && die "A distribution with the supplied name already exists."
        write_settings
        import_tar "$tar" || die "import failed"
        clear_image_journal
        unique_machine_id
        sync_hostname
        echo "The operation completed successfully."
        exit 0 ;;
    --export)
        check_name "${2:-}"
        machinectl export-tar "$M" "${3:?export file}" ; exit $? ;;
    -t|--terminate)
        check_name "${2:-}"
        stop_machine || die "could not stop $M"
        exit 0 ;;
    --shutdown)
        # Never global: a Linux host's other containers are not ours to stop.
        echo "hydrogen-workspace: --shutdown stops $M only" >&2
        stop_machine; exit $? ;;
    --unregister)
        check_name "${2:-}"
        stop_machine || die "could not stop $M"
        if image_present; then machinectl remove "$M" >/dev/null 2>&1 || remove_tree "$POOL/$M"; fi
        image_present && die "could not remove $POOL/$M"
        rm -f "$SETTINGS"
        command -v nft >/dev/null 2>&1 && nft delete table inet adom_hydrogen >/dev/null 2>&1
        echo "Unregistering. The operation completed successfully."
        exit 0 ;;
    --set-default-user|--set-default|-s|--set-version|--manage|--update|--install)
        exit 0 ;;
    -d|--distribution)
        check_name "${2:-}"; shift 2
        user=adom
        while [ $# -gt 0 ]; do
            case "$1" in
                -u|--user) user=$2; shift 2 ;;
                -e|--exec|--) shift; break ;;
                --cd) shift 2 ;;
                *) break ;;
            esac
        done
        exec_in "$user" "$@" ;;
    *) die "unsupported argument: $1" ;;
esac
