#!/usr/bin/env bash
set -euo pipefail

RUNTIME_VERSION="1helm-oci-runtime-v1"
RUNTIME_MANIFEST="${HELM_OCI_RUNTIME_MANIFEST:-/etc/1helm/oci-runtime-v1.conf}"
[[ -r "$RUNTIME_MANIFEST" ]] || { echo "1Helm OCI runtime: runtime manifest is missing" >&2; exit 1; }
# shellcheck source=/dev/null
source "$RUNTIME_MANIFEST"
if [[ -n "${HELM_OCI_STATE_ROOT_OVERRIDE:-}" ]]; then
  [[ "${EUID}" -eq 0 && -z "${SUDO_USER:-}" ]] || { echo "1Helm OCI runtime: state override is development-only" >&2; exit 1; }
  ONEHELM_OCI_STATE_ROOT="$HELM_OCI_STATE_ROOT_OVERRIDE"
fi
if [[ -n "${HELM_OCI_CONTAINERFILE_OVERRIDE:-}" ]]; then
  [[ "${EUID}" -eq 0 && -z "${SUDO_USER:-}" ]] || { echo "1Helm OCI runtime: recipe override is development-only" >&2; exit 1; }
  ONEHELM_OCI_CONTAINERFILE="$HELM_OCI_CONTAINERFILE_OVERRIDE"
fi
if [[ -n "${HELM_OCI_IMAGE_ARCHIVE_OVERRIDE:-}" ]]; then
  [[ "${EUID}" -eq 0 && -z "${SUDO_USER:-}" ]] || { echo "1Helm OCI runtime: image archive override is development-only" >&2; exit 1; }
  ONEHELM_OCI_IMAGE_ARCHIVE="$HELM_OCI_IMAGE_ARCHIVE_OVERRIDE"
fi
if [[ -n "${HELM_OCI_IMAGE_SHA256_FILE_OVERRIDE:-}" ]]; then
  [[ "${EUID}" -eq 0 && -z "${SUDO_USER:-}" ]] || { echo "1Helm OCI runtime: image digest override is development-only" >&2; exit 1; }
  ONEHELM_OCI_IMAGE_SHA256_FILE="$HELM_OCI_IMAGE_SHA256_FILE_OVERRIDE"
fi

die() { printf '1Helm OCI runtime: %s\n' "$*" >&2; exit 1; }
[[ "${ONEHELM_OCI_RUNTIME_VERSION:-}" == "$RUNTIME_VERSION" ]] || die "runtime manifest version mismatch"
[[ "${ONEHELM_OCI_STATE_ROOT:-}" =~ ^/.+/runtime/oci$ ]] || die "unsafe runtime state root"
[[ "${ONEHELM_OCI_RUN_ROOT:-}" == /run/1helm-oci ]] || die "unsafe runtime run root"
[[ "${ONEHELM_OCI_CONTAINERFILE:-}" == /* ]] || die "unsafe container recipe path"
[[ "${ONEHELM_OCI_IMAGE_ARCHIVE:-}" == /* ]] || die "unsafe channel image archive path"
[[ "${ONEHELM_OCI_IMAGE_SHA256_FILE:-}" == /* ]] || die "unsafe channel image digest path"
[[ "${ONEHELM_OCI_SERVICE_USER:-}" =~ ^[a-z0-9_][a-z0-9_-]*$ ]] || die "unsafe service account"
[[ "${ONEHELM_OCI_AGENT_UID:-}" =~ ^[0-9]+$ && "${ONEHELM_OCI_AGENT_GID:-}" =~ ^[0-9]+$ ]] || die "invalid agent identity"

STATE_ROOT="$ONEHELM_OCI_STATE_ROOT"
RUN_ROOT="$ONEHELM_OCI_RUN_ROOT"
CONTAINERFILE="$ONEHELM_OCI_CONTAINERFILE"
IMAGE_ARCHIVE="$ONEHELM_OCI_IMAGE_ARCHIVE"
IMAGE_SHA256_FILE="$ONEHELM_OCI_IMAGE_SHA256_FILE"
AGENT_UID="$ONEHELM_OCI_AGENT_UID"
AGENT_GID="$ONEHELM_OCI_AGENT_GID"
STORAGE_ROOT="$STATE_ROOT/storage"
CHANNELS_ROOT="$STATE_ROOT/channels"
BACKUPS_ROOT="$STATE_ROOT/backups"
NETWORKS_ROOT="$STATE_ROOT/networks"
LIBPOD_TMP="$RUN_ROOT/libpod"
RUNTIME_USER_ROOT="$RUN_ROOT/user"
RUNTIME_TMP="$RUN_ROOT/tmp"
# Rootful Podman/netavark otherwise falls back to /var/tmp/podman-run-0 when
# invoked by the systemd service. PrivateTmp makes that netns path disappear
# after service restart, leaving a "running" container whose network namespace
# cannot be rejoined. Pin every runtime/netns path under the service's explicit
# /run/1helm-oci allowance so helpers launched before and after restart agree.
export XDG_RUNTIME_DIR="$RUNTIME_USER_ROOT"
# sudo strips the service TMPDIR. Set it again inside the root-owned helper so
# Podman image import never falls back to read-only /var/tmp under ProtectSystem.
export TMPDIR="$RUNTIME_TMP"
PODMAN=(podman --root "$STORAGE_ROOT" --runroot "$RUN_ROOT" --network-config-dir "$NETWORKS_ROOT" --tmpdir "$LIBPOD_TMP" --cgroup-manager=systemd --events-backend=file --log-level=error)

valid_name() { [[ "${1:-}" =~ ^1helm-[a-f0-9]{16}-channel-[0-9]+$ ]]; }
valid_owner() { [[ "${1:-}" =~ ^[a-f0-9]{16}:[0-9]+$ ]]; }
valid_image() { [[ "${1:-}" =~ ^local/1helm-channel-(machine|restored):[A-Za-z0-9._-]+$ ]]; }
podman_image() { valid_image "$1" || die "invalid image reference"; printf 'localhost/%s' "$1"; }
valid_resources() {
  [[ "${1:-}" =~ ^[1-8]$ && "${2:-}" =~ ^[0-9]+$ ]] || return 1
  (($2 >= 1024 && $2 <= 16384))
}
owner_installation() { printf '%s' "${1%%:*}"; }
owner_channel() { printf '%s' "${1#*:}"; }
channel_root() { printf '%s/%s' "$CHANNELS_ROOT" "$1"; }
network_name() { printf '1helm-%s' "$(owner_installation "$1")"; }

ensure_netavark_backend() (
  local backend_file="$1" backend_dir candidate backend_lock_fd
  backend_dir="$(dirname "$backend_file")"
  { command -v netavark >/dev/null 2>&1 || [[ -x /usr/lib/podman/netavark || -x /usr/libexec/podman/netavark ]]; } || return 0

  # Serialize the inspection and replacement so concurrent starts do not replace
  # an exact selector a second time. The candidate stays beside its destination,
  # and only a complete root-owned 0600 file is atomically promoted.
  exec {backend_lock_fd}<"$backend_dir"
  flock "$backend_lock_fd"
  if [[ -L "$backend_file" ]]; then
    return 0
  elif [[ -f "$backend_file" ]]; then
    cmp -s -- "$backend_file" <(printf '%s' netavark) && return 0
    if [[ -s "$backend_file" ]] && ! cmp -s -- "$backend_file" <(printf 'netavark\n'); then
      return 0
    fi
  elif [[ -e "$backend_file" ]]; then
    return 0
  fi

  candidate="$(mktemp "$backend_dir/.defaultNetworkBackend.XXXXXX")"
  if ! printf '%s' netavark >"$candidate" \
      || ! chown root:root "$candidate" \
      || ! chmod 0600 "$candidate"; then
    rm -f -- "$candidate"
    return 1
  fi
  if ! mv -f -- "$candidate" "$backend_file"; then
    rm -f -- "$candidate"
    return 1
  fi
)

ensure_roots() {
  install -d -m 0711 "$STATE_ROOT" "$CHANNELS_ROOT"
  install -d -m 0700 "$STORAGE_ROOT" "$BACKUPS_ROOT" "$NETWORKS_ROOT"
  install -d -m 0755 "$RUN_ROOT" "$LIBPOD_TMP"
  install -d -o root -g root -m 0700 "$RUNTIME_USER_ROOT"
  install -d -o root -g root -m 1777 "$RUNTIME_TMP"
  # Prefer netavark on a fresh dedicated store. CNI writes IPAM state beneath
  # /var/lib/cni, which is intentionally read-only to the hardened service;
  # netavark keeps its runtime state under the explicit Podman runroot. Repair
  # only the empty and historical newline forms; every other selection is kept.
  ensure_netavark_backend "$STORAGE_ROOT/defaultNetworkBackend"
}

container_exists() { "${PODMAN[@]}" container exists "$1" >/dev/null 2>&1; }
container_state() {
  container_exists "$1" || { printf 'missing'; return; }
  "${PODMAN[@]}" inspect --type container --format '{{.State.Status}}' "$1"
}

verify_storage() {
  local name="$1" owner="$2" root expected identity_stat
  valid_name "$name" && valid_owner "$owner" || die "invalid container identity"
  [[ "${name#1helm-}" == "$(owner_installation "$owner")-channel-$(owner_channel "$owner")" ]] || die "container name and owner do not match"
  root="$(channel_root "$name")"
  expected="$STATE_ROOT/channels/$name"
  [[ "$root" == "$expected" && -d "$root/workspace" && -d "$root/files" && -d "$root/home" && -d "$root/var-lib-1helm" ]] || die "channel storage is missing"
  [[ ! -L "$root" && "$(stat -c '%u:%g:%a' "$root")" == "0:0:711" ]] || die "channel storage root permissions do not match"
  [[ -f "$root/var-lib-1helm/owner" && "$(tr -d '\r\n' <"$root/var-lib-1helm/owner")" == "$owner" ]] || die "ownership marker does not match"
  [[ -f "$root/network.json" && ! -L "$root/network.json" ]] || die "network identity is missing"
  identity_stat="$(stat -c '%u:%g:%a' "$root/network.json")"
  [[ "$identity_stat" == "0:0:600" ]] || die "network identity permissions do not match"
}

verify_container() {
  local name="$1" owner="$2" root network container network_data identity
  verify_storage "$name" "$owner"
  container_exists "$name" || die "container does not exist"
  root="$(channel_root "$name")"
  network="$(network_name "$owner")"
  "${PODMAN[@]}" network exists "$network" || die "owned network does not exist"
  container="$("${PODMAN[@]}" inspect --type container "$name")"
  network_data="$("${PODMAN[@]}" network inspect "$network")"
  identity="$(<"$root/network.json")"
  python3 - "$container" "$network_data" "$identity" "$root" "$name" "$owner" "$network" <<'PY'
import ipaddress, json, os, re, sys

rows=json.loads(sys.argv[1])
networks=json.loads(sys.argv[2])
identity=json.loads(sys.argv[3])
root=os.path.realpath(sys.argv[4])
name, owner, network=sys.argv[5:8]
if not isinstance(rows,list) or len(rows) != 1: raise SystemExit("container metadata is invalid")
if not isinstance(networks,list) or len(networks) != 1: raise SystemExit("owned network metadata is invalid")
row=rows[0]
network_row=networks[0]
if str((row.get("Config") or {}).get("Hostname") or "") != name:
    raise SystemExit("container hostname does not match")
labels=(row.get("Config") or {}).get("Labels") or {}
expected_labels={"com.1helm.managed":"true","com.1helm.owner":owner,"com.1helm.machine":name}
if any(str(labels.get(key,"")) != value for key,value in expected_labels.items()):
    raise SystemExit("container labels do not match")
network_labels=network_row.get("labels") or network_row.get("Labels") or {}
if network_labels.get("com.1helm.managed") != "true" or network_labels.get("com.1helm.installation") != owner.split(":",1)[0]:
    raise SystemExit("network ownership labels do not match")
subnets=network_row.get("subnets") or network_row.get("Subnets") or []
if len(subnets) != 1: raise SystemExit("owned network must have exactly one subnet")
subnet=ipaddress.ip_network(str(subnets[0].get("subnet") or subnets[0].get("Subnet") or ""), strict=True)
gateway=ipaddress.ip_address(str(subnets[0].get("gateway") or subnets[0].get("Gateway") or ""))
if subnet.version != 4 or gateway not in subnet or gateway in {subnet.network_address, subnet.broadcast_address}:
    raise SystemExit("owned network IPv4 metadata is invalid")
expected_identity={"container":name,"owner":owner,"network":network,"subnet":str(subnet),"gateway":str(gateway)}
if set(identity) != {*expected_identity,"ip","mac"} or any(str(identity.get(key,"")) != value for key,value in expected_identity.items()):
    raise SystemExit("network identity does not match this channel")
try: ip=ipaddress.ip_address(str(identity["ip"]))
except ValueError: raise SystemExit("network identity IP is invalid")
mac=str(identity["mac"])
if ip not in subnet or ip in {subnet.network_address, subnet.broadcast_address, gateway}:
    raise SystemExit("network identity IP is outside the owned subnet")
if not re.fullmatch(r"02(?::[0-9a-f]{2}){5}", mac):
    raise SystemExit("network identity MAC is invalid")

mounts=row.get("Mounts") or []
expected={
    "/workspace":os.path.join(root,"workspace"),
    "/workspace/files":os.path.join(root,"files"),
    "/home/agent":os.path.join(root,"home"),
    "/var/lib/1helm":os.path.join(root,"var-lib-1helm"),
}
actual={str(m.get("Destination") or m.get("destination")):os.path.realpath(str(m.get("Source") or m.get("source") or "")) for m in mounts}
if actual != expected:
    raise SystemExit("container storage mounts do not match")

attached=(row.get("NetworkSettings") or {}).get("Networks") or {}
if set(attached) != {network}: raise SystemExit("container network attachment does not match")
attachment=attached[network] or {}
network_id=str(network_row.get("id") or network_row.get("ID") or network_row.get("network_id") or "").strip()
attached_id=str(attachment.get("NetworkID") or attachment.get("network_id") or "").strip()

def option_values(flag):
    command=(row.get("Config") or {}).get("CreateCommand") or []
    values=[]
    for index, value in enumerate(command):
        value=str(value)
        if value == flag:
            if index + 1 >= len(command): raise SystemExit(f"container create option {flag} has no value")
            values.append(str(command[index+1]))
        elif value.startswith(flag+"="):
            values.append(value.split("=",1)[1])
    return values
if option_values("--network") != [network] or option_values("--ip") != [str(ip)] or option_values("--mac-address") != [mac]:
    raise SystemExit("container static network creation contract does not match")

def network_ids_compatible(declared, observed, network_name):
    """Podman/netavark may use full id, short id, network name, or leave NetworkID empty until start."""
    declared=(declared or "").strip().lower()
    observed=(observed or "").strip().lower()
    name=(network_name or "").strip().lower()
    if not declared and not observed:
        return True
    if observed and observed == name:
        return True
    if declared and observed and declared == observed:
        return True
    if declared and observed and (declared.startswith(observed) or observed.startswith(declared)):
        return True
    return False

state=str((row.get("State") or {}).get("Status") or "")
if state == "running":
    if not network_id or not network_ids_compatible(network_id, attached_id, network):
        raise SystemExit("container network ID does not match")
    if str(attachment.get("IPAddress") or "") != str(ip) or str(attachment.get("MacAddress") or "").lower() != mac:
        raise SystemExit("running container network identity does not match")
    prefix=int(attachment.get("IPPrefixLen") or 0)
    if ipaddress.ip_network(f"{ip}/{prefix}", strict=False) != subnet:
        raise SystemExit("running container subnet does not match")
elif attached_id and network_id and not network_ids_compatible(network_id, attached_id, network):
    # Created-but-not-running containers sometimes omit NetworkID; only fail when both sides are present and conflict.
    raise SystemExit("container network ID does not match")
PY
}

# Docker (and some host firewalls) set FORWARD policy DROP and only punch holes
# for their own bridges. 1Helm's netavark networks need explicit accept + NAT so
# resident guests can reach package mirrors and the public internet. Prefer the
# DOCKER-USER chain when present so rules stay ahead of Docker's DROP path.
ensure_guest_egress() {
  local network="$1" bridge subnet network_json
  command -v iptables >/dev/null || die "iptables is required for channel computer internet access"
  # Rootful netavark needs host IPv4 forwarding.
  if [[ "$(sysctl -n net.ipv4.ip_forward 2>/dev/null || echo 0)" != "1" ]]; then
    sysctl -w net.ipv4.ip_forward=1 >/dev/null
  fi
  network_json="$("${PODMAN[@]}" network inspect "$network")"
  read -r bridge subnet < <(python3 -c '
import json, sys
rows=json.loads(sys.argv[1])
if not isinstance(rows, list) or not rows: raise SystemExit("owned network metadata is invalid")
row=rows[0]
bridge=str(row.get("network_interface") or row.get("NetworkInterface") or "")
subnets=row.get("subnets") or row.get("Subnets") or []
if not subnets: raise SystemExit("owned network subnet is missing")
subnet=str(subnets[0].get("subnet") or subnets[0].get("Subnet") or "")
if not bridge or bridge == "<no value>": raise SystemExit("owned network interface is missing")
if "/" not in subnet: raise SystemExit("owned network subnet is invalid")
print(bridge, subnet)
' "$network_json") || die "owned network interface/subnet could not be resolved"

  insert_if_missing() {
    local table="${1:-filter}" chain="$2"; shift 2
    if [[ "$table" == filter ]]; then
      iptables -C "$chain" "$@" 2>/dev/null || iptables -I "$chain" 1 "$@"
    else
      iptables -t "$table" -C "$chain" "$@" 2>/dev/null || iptables -t "$table" -I "$chain" 1 "$@"
    fi
  }

  # Accept guest→world and established replies. Insert at head so Docker DROP cannot bury them.
  if iptables -nL DOCKER-USER >/dev/null 2>&1; then
    insert_if_missing filter DOCKER-USER -i "$bridge" -j ACCEPT
    insert_if_missing filter DOCKER-USER -o "$bridge" -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  fi
  insert_if_missing filter FORWARD -i "$bridge" -j ACCEPT
  insert_if_missing filter FORWARD -o "$bridge" -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  # SNAT guest traffic leaving the host (not hairpin back onto the bridge).
  insert_if_missing nat POSTROUTING -s "$subnet" ! -o "$bridge" -j MASQUERADE
}

ensure_network() {
  local owner="$1" installation network labels bridge_name network_path
  installation="$(owner_installation "$owner")"
  network="1helm-$installation"
  network_path="$NETWORKS_ROOT/$network.json"
  # Linux IFNAMSIZ is 15 chars; keep a stable, installation-scoped bridge name.
  bridge_name="1h${installation:0:12}"
  if "${PODMAN[@]}" network exists "$network"; then
    labels="$("${PODMAN[@]}" network inspect --format '{{json .Labels}}' "$network")"
    python3 - "$labels" "$installation" <<'PY'
import json, sys
labels=json.loads(sys.argv[1] or "{}")
if labels.get("com.1helm.managed") != "true" or labels.get("com.1helm.installation") != sys.argv[2]:
    raise SystemExit("network ownership labels do not match")
PY
    # Netavark 1.4 starts aardvark-dns through a user systemd scope. A root
    # helper invoked by the system service has no user bus, so the advertised
    # gateway DNS listener never exists and every resident lookup times out.
    # These are 1Helm-owned JSON network definitions; disable only that broken
    # plugin and let containers inherit the host's working resolvers instead.
    if [[ -f "$network_path" && ! -L "$network_path" ]] \
        && grep -q '"dns_enabled"[[:space:]]*:[[:space:]]*true' "$network_path"; then
      python3 - "$network_path" <<'PY'
import json, os, stat, sys, tempfile
path=sys.argv[1]
info=os.lstat(path)
if not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode) or info.st_uid != 0 or info.st_gid != 0:
    raise SystemExit("owned network definition is not a safe root-owned file")
with open(path, encoding="utf-8") as source: network=json.load(source)
labels=network.get("labels") or network.get("Labels") or {}
if labels.get("com.1helm.managed") != "true": raise SystemExit("refusing to change an unmanaged network")
network["dns_enabled"]=False
descriptor,candidate=tempfile.mkstemp(prefix=".1helm-network-",dir=os.path.dirname(path))
try:
    with os.fdopen(descriptor,"w",encoding="utf-8") as destination:
        json.dump(network,destination,indent=5); destination.write("\n"); destination.flush(); os.fsync(destination.fileno())
    os.chmod(candidate,stat.S_IMODE(info.st_mode)); os.chown(candidate,0,0); os.replace(candidate,path)
finally:
    if os.path.exists(candidate): os.unlink(candidate)
PY
    fi
  else
    # Prefer a stable IFNAMSIZ-safe bridge name when the backend supports Docker-
    # style bridge options (netavark). Debian bookworm's CNI backend rejects
    # com.docker.network.bridge.name; fall back to a labeled default bridge and
    # let ensure_guest_egress read the real interface from network inspect.
    create_out=""
    if ! create_out="$("${PODMAN[@]}" network create --disable-dns \
      --opt "com.docker.network.bridge.name=${bridge_name}" \
      --label com.1helm.managed=true --label "com.1helm.installation=$installation" "$network" 2>&1)"; then
      if grep -qiE 'unsupported (bridge )?network option|unknown network option' <<<"$create_out"; then
        "${PODMAN[@]}" network create --disable-dns \
          --label com.1helm.managed=true --label "com.1helm.installation=$installation" "$network" >/dev/null \
          || die "channel network could not be created"
      else
        printf '%s\n' "$create_out" >&2
        die "channel network could not be created"
      fi
    fi
  fi
  ensure_guest_egress "$network"
  printf '%s' "$network"
}

ensure_network_identity() {
  local name="$1" owner="$2" network="$3" root identity_path network_data lock_path identity lock_fd
  root="$(channel_root "$name")"
  identity_path="$root/network.json"
  lock_path="$STATE_ROOT/network.lock"
  [[ ! -e "$lock_path" || (-f "$lock_path" && ! -L "$lock_path") ]] || die "network identity lock is not a safe file"
  exec {lock_fd}>"$lock_path"
  chmod 0600 "$lock_path"
  flock "$lock_fd"
  network_data="$("${PODMAN[@]}" network inspect "$network")"
  identity="$(python3 - "$network_data" "$identity_path" "$CHANNELS_ROOT" "$name" "$owner" "$network" <<'PY'
import glob, hashlib, ipaddress, json, os, re, stat, sys

network_rows=json.loads(sys.argv[1])
identity_path, channels_root, name, owner, network_name=sys.argv[2:7]
if not isinstance(network_rows,list) or len(network_rows) != 1: raise SystemExit("owned network metadata is invalid")
network_row=network_rows[0]
labels=network_row.get("labels") or network_row.get("Labels") or {}
installation=owner.split(":",1)[0]
if labels.get("com.1helm.managed") != "true" or labels.get("com.1helm.installation") != installation:
    raise SystemExit("network ownership labels do not match")
if str(network_row.get("name") or network_row.get("Name") or "") != network_name:
    raise SystemExit("owned network name does not match")
subnets=network_row.get("subnets") or network_row.get("Subnets") or []
if len(subnets) != 1: raise SystemExit("owned network must have exactly one subnet")
try:
    subnet=ipaddress.ip_network(str(subnets[0].get("subnet") or subnets[0].get("Subnet") or ""), strict=True)
    gateway=ipaddress.ip_address(str(subnets[0].get("gateway") or subnets[0].get("Gateway") or ""))
except ValueError: raise SystemExit("owned network IPv4 metadata is invalid")
if subnet.version != 4 or not 16 <= subnet.prefixlen <= 28 or gateway not in subnet or gateway in {subnet.network_address,subnet.broadcast_address}:
    raise SystemExit("owned network IPv4 metadata is invalid")

expected={"container":name,"owner":owner,"network":network_name,"subnet":str(subnet),"gateway":str(gateway)}
mac_pattern=re.compile(r"02(?::[0-9a-f]{2}){5}")
def validate(value, expected_fields):
    if not isinstance(value,dict) or set(value) != {*expected_fields,"ip","mac"}: raise SystemExit("network identity fields do not match")
    if any(str(value.get(key,"")) != expected_value for key,expected_value in expected_fields.items()): raise SystemExit("network identity does not match this channel")
    try: address=ipaddress.ip_address(str(value["ip"]))
    except ValueError: raise SystemExit("network identity IP is invalid")
    mac=str(value["mac"])
    if address not in subnet or address in {subnet.network_address,subnet.broadcast_address,gateway}: raise SystemExit("network identity IP is outside the owned subnet")
    if not mac_pattern.fullmatch(mac): raise SystemExit("network identity MAC is invalid")
    return address,mac

used_ips=set()
used_macs=set()
prefix=os.path.join(channels_root,f"1helm-{installation}-channel-*")
for channel_path in glob.glob(prefix):
    if os.path.realpath(channel_path) == os.path.realpath(os.path.dirname(identity_path)): continue
    other_path=os.path.join(channel_path,"network.json")
    if not os.path.exists(other_path): continue
    info=os.lstat(other_path)
    if not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode) or info.st_uid != 0 or info.st_gid != 0 or stat.S_IMODE(info.st_mode) != 0o600:
        raise SystemExit("another channel network identity is not a safe root-owned file")
    try: other=json.load(open(other_path,encoding="utf-8"))
    except (OSError,json.JSONDecodeError): raise SystemExit("another channel network identity is invalid")
    other_name=os.path.basename(channel_path)
    match=re.fullmatch(rf"1helm-{installation}-channel-([0-9]+)",other_name)
    if not match: raise SystemExit("another channel storage identity is invalid")
    other_expected={"container":other_name,"owner":f"{installation}:{match.group(1)}","network":network_name,"subnet":str(subnet),"gateway":str(gateway)}
    other_ip,other_mac=validate(other,other_expected)
    if other_ip in used_ips or other_mac in used_macs: raise SystemExit("channel network identities collide")
    used_ips.add(other_ip); used_macs.add(other_mac)

for attached in (network_row.get("containers") or network_row.get("Containers") or {}).values():
    for interface in (attached.get("interfaces") or attached.get("Interfaces") or {}).values():
        for row in interface.get("subnets") or interface.get("Subnets") or []:
            raw=str(row.get("ipnet") or row.get("IPNet") or "").split("/",1)[0]
            if raw:
                try: used_ips.add(ipaddress.ip_address(raw))
                except ValueError: raise SystemExit("owned network has an invalid attached IP")
        raw_mac=str(interface.get("mac_address") or interface.get("MacAddress") or "").lower()
        if raw_mac: used_macs.add(raw_mac)

if os.path.exists(identity_path):
    info=os.lstat(identity_path)
    if not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode) or info.st_uid != 0 or info.st_gid != 0 or stat.S_IMODE(info.st_mode) != 0o600:
        raise SystemExit("network identity is not a safe root-owned file")
    try: identity=json.load(open(identity_path,encoding="utf-8"))
    except (OSError,json.JSONDecodeError): raise SystemExit("network identity is invalid")
    address,mac=validate(identity,expected)
    if address in used_ips or mac in used_macs: raise SystemExit("network identity collides with another channel")
else:
    seed=hashlib.sha256(f"{network_name}\0{name}\0{owner}".encode()).digest()
    first=int(subnet.network_address)+1
    count=subnet.num_addresses-2
    offset=int.from_bytes(seed[:8],"big") % count
    address=None
    for step in range(count):
        candidate=ipaddress.ip_address(first+((offset+step)%count))
        if candidate != gateway and candidate not in used_ips:
            address=candidate
            break
    if address is None: raise SystemExit("owned network has no free channel address")
    mac=None
    for attempt in range(256):
        digest=hashlib.sha256(seed+attempt.to_bytes(2,"big")).digest()
        candidate="02:"+":".join(f"{byte:02x}" for byte in digest[:5])
        if candidate not in used_macs:
            mac=candidate
            break
    if mac is None: raise SystemExit("could not allocate a unique channel MAC")
    identity={**expected,"ip":str(address),"mac":mac}
    descriptor=os.open(identity_path,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
    with os.fdopen(descriptor,"w",encoding="utf-8") as destination:
        json.dump(identity,destination,sort_keys=True,separators=(",",":"))
        destination.write("\n")
        destination.flush(); os.fsync(destination.fileno())
print(identity["ip"],identity["mac"])
PY
)" || die "channel network identity could not be established"
  flock -u "$lock_fd"
  exec {lock_fd}>&-
  printf '%s' "$identity"
}

grant_shared_access() {
  local shared="$1" service_uid=""
  [[ -d "$shared" && ! -L "$shared" ]] || die "shared channel storage is not a safe directory"
  if id "$ONEHELM_OCI_SERVICE_USER" >/dev/null 2>&1; then
    service_uid="$(id -u "$ONEHELM_OCI_SERVICE_USER")"
  fi
  while IFS= read -r -d '' directory; do
    if [[ -n "$service_uid" ]]; then
      setfacl -m "u:$AGENT_UID:rwx,u:$service_uid:rwx,m::rwx,d:u:$AGENT_UID:rwx,d:u:$service_uid:rwx,d:m::rwx" "$directory"
    else
      setfacl -m "u:$AGENT_UID:rwx,m::rwx,d:u:$AGENT_UID:rwx,d:m::rwx" "$directory"
    fi
  done < <(find -P "$shared" -xdev -type d -print0)
  while IFS= read -r -d '' entry; do
    if [[ -n "$service_uid" ]]; then
      setfacl -m "u:$AGENT_UID:rw-,u:$service_uid:rw-,m::rw-" "$entry"
    else
      setfacl -m "u:$AGENT_UID:rw-,m::rw-" "$entry"
    fi
  done < <(find -P "$shared" -xdev -type f -print0)
}

prepare_storage() {
  local name="$1" owner="$2" root shared
  valid_name "$name" && valid_owner "$owner" || die "invalid container identity"
  [[ "${name#1helm-}" == "$(owner_installation "$owner")-channel-$(owner_channel "$owner")" ]] || die "container name and owner do not match"
  root="$(channel_root "$name")"
  if [[ -e "$root" ]]; then
    [[ -d "$root" && ! -L "$root" ]] || die "channel storage is not a safe directory"
    [[ ! -e "$root/var-lib-1helm/owner" || "$(tr -d '\r\n' <"$root/var-lib-1helm/owner")" == "$owner" ]] || die "existing channel storage has a different owner"
  fi
  install -d -o root -g root -m 0711 "$root"
  # Agent-owned workspace/files. On Windows, Files/Cowork never touch this tree
  # via \\wsl.localhost (interop=false kills 9p); they use the storage_* helper
  # operations instead. Keep modes tight.
  install -d -o "$AGENT_UID" -g "$AGENT_GID" -m 0700 "$root/workspace" "$root/files" "$root/home"
  chown -R "$AGENT_UID:$AGENT_GID" "$root/workspace" "$root/files" "$root/home"
  install -d -o root -g root -m 0700 "$root/var-lib-1helm"
  printf '%s\n' "$owner" >"$root/var-lib-1helm/owner"
  chmod 0600 "$root/var-lib-1helm/owner"
  for shared in "$root/workspace" "$root/files" "$root/home"; do grant_shared_access "$shared"; done
}

# Resolve a Files/Cowork relative path into an absolute, containment-checked
# path under the channel's workspace/ or files/ tree. Empty path is the tree root.
resolve_storage_path() {
  local name="$1" area="$2" rel="$3" root base candidate
  root="$(channel_root "$name")"
  case "$area" in
    workspace) base="$root/workspace" ;;
    files) base="$root/files" ;;
    *) die "invalid storage area" ;;
  esac
  [[ -d "$base" && ! -L "$base" ]] || die "storage area is missing"
  if [[ -z "$rel" || "$rel" == "." ]]; then
    printf '%s' "$base"
    return
  fi
  # Reject absolute paths. Multi-dot filenames are fine (board.whiteboard.json,
  # deck.slides.json); only whole-segment "." / ".." are blocked.
  [[ "$rel" != /* ]] || die "unsafe storage path"
  local segment
  IFS='/' read -r -a segments <<<"$rel"
  for segment in "${segments[@]}"; do
    [[ -n "$segment" ]] || die "unsafe storage path"
    [[ "$segment" != "." && "$segment" != ".." ]] || die "unsafe storage path"
    # Allow letters, digits, dot, underscore, hyphen, space. No slashes (already split).
    if [[ ! "$segment" =~ ^[A-Za-z0-9._\ -]+$ ]]; then
      die "unsafe storage path"
    fi
  done
  candidate="$base/$rel"
  # Containment: realpath of candidate must stay under realpath of base.
  local real_base real_candidate parent
  real_base="$(realpath -m "$base")"
  if [[ -e "$candidate" || -L "$candidate" ]]; then
    real_candidate="$(realpath -m "$candidate")"
  else
    parent="$(realpath -m "$(dirname "$candidate")")"
    [[ "$parent" == "$real_base" || "$parent" == "$real_base"/* ]] || die "storage path escapes channel tree"
    real_candidate="$parent/$(basename "$candidate")"
  fi
  [[ "$real_candidate" == "$real_base" || "$real_candidate" == "$real_base"/* ]] || die "storage path escapes channel tree"
  # Refuse any symlink component along the path.
  local cursor="$real_base" part
  IFS='/' read -r -a parts <<<"${real_candidate#"$real_base"/}"
  if [[ "$real_candidate" != "$real_base" ]]; then
    for part in "${parts[@]}"; do
      [[ -n "$part" ]] || continue
      cursor="$cursor/$part"
      if [[ -L "$cursor" ]]; then die "storage path must not traverse symlinks"; fi
    done
  fi
  printf '%s' "$real_candidate"
}

storage_list() {
  local name="$1" owner="$2" area="$3" rel="${4:-}" path
  verify_storage "$name" "$owner"
  path="$(resolve_storage_path "$name" "$area" "$rel")"
  [[ -d "$path" && ! -L "$path" ]] || die "Folder not found."
  python3 - "$path" <<'PY'
import json, os, sys
path = sys.argv[1]
entries = []
for name in sorted(os.listdir(path)):
    full = os.path.join(path, name)
    if os.path.islink(full):
        continue
    if os.path.isdir(full):
        st = os.stat(full)
        entries.append({"name": name, "kind": "directory", "size": 0, "modified": int(st.st_mtime * 1000)})
    elif os.path.isfile(full):
        st = os.stat(full)
        entries.append({"name": name, "kind": "file", "size": int(st.st_size), "modified": int(st.st_mtime * 1000)})
print(json.dumps({"entries": entries}, separators=(",", ":")))
PY
}

storage_stat() {
  local name="$1" owner="$2" area="$3" rel="${4:-}" path
  verify_storage "$name" "$owner"
  path="$(resolve_storage_path "$name" "$area" "$rel")"
  [[ -e "$path" && ! -L "$path" ]] || die "File or folder not found."
  python3 - "$path" <<'PY'
import json, os, sys
path = sys.argv[1]
st = os.stat(path)
kind = "directory" if os.path.isdir(path) else "file" if os.path.isfile(path) else "other"
print(json.dumps({
  "name": os.path.basename(path) or ".",
  "kind": kind,
  "size": 0 if kind == "directory" else int(st.st_size),
  "modified": int(st.st_mtime * 1000),
  "exists": True,
}, separators=(",", ":")))
PY
}

storage_mkdir() {
  local name="$1" owner="$2" area="$3" rel="$4" path parent
  verify_storage "$name" "$owner"
  [[ -n "$rel" ]] || die "mkdir requires a path"
  path="$(resolve_storage_path "$name" "$area" "$rel")"
  parent="$(dirname "$path")"
  [[ -d "$parent" && ! -L "$parent" ]] || die "Parent folder not found."
  [[ ! -e "$path" ]] || die "A file or folder with that name already exists."
  install -d -o "$AGENT_UID" -g "$AGENT_GID" -m 0700 "$path"
  storage_stat "$name" "$owner" "$area" "$rel"
}

storage_write() {
  local name="$1" owner="$2" area="$3" rel="$4" mode="${5:-overwrite}" path parent
  verify_storage "$name" "$owner"
  [[ -n "$rel" ]] || die "write requires a path"
  path="$(resolve_storage_path "$name" "$area" "$rel")"
  parent="$(dirname "$path")"
  [[ -d "$parent" && ! -L "$parent" ]] || die "Parent folder not found."
  if [[ "$mode" == "create" && -e "$path" ]]; then die "A file or folder with that name already exists."; fi
  if [[ -e "$path" && ( -L "$path" || -d "$path" ) ]]; then die "Choose a file to edit."; fi
  # Body arrives on stdin (binary-safe).
  cat >"$path"
  chown "$AGENT_UID:$AGENT_GID" "$path"
  chmod 0600 "$path"
  storage_stat "$name" "$owner" "$area" "$rel"
}

storage_read() {
  local name="$1" owner="$2" area="$3" rel="$4" path
  verify_storage "$name" "$owner"
  [[ -n "$rel" ]] || die "read requires a path"
  path="$(resolve_storage_path "$name" "$area" "$rel")"
  [[ -f "$path" && ! -L "$path" ]] || die "File not found."
  cat -- "$path"
}

storage_rm() {
  local name="$1" owner="$2" area="$3" rel="$4" recursive="${5:-0}" path
  verify_storage "$name" "$owner"
  [[ -n "$rel" ]] || die "rm requires a path"
  path="$(resolve_storage_path "$name" "$area" "$rel")"
  local base
  base="$(resolve_storage_path "$name" "$area" "")"
  [[ "$path" != "$base" ]] || die "Refusing to remove the storage root."
  [[ -e "$path" && ! -L "$path" ]] || die "File or folder not found."
  if [[ -d "$path" ]]; then
    [[ "$recursive" == "1" ]] || die "Folder is not empty; remove recursively."
    rm -rf -- "$path"
  else
    rm -f -- "$path"
  fi
  printf '{"ok":true}\n'
}

storage_rename() {
  local name="$1" owner="$2" area="$3" from_rel="$4" to_rel="$5" from to to_parent
  verify_storage "$name" "$owner"
  [[ -n "$from_rel" && -n "$to_rel" ]] || die "rename requires source and destination"
  from="$(resolve_storage_path "$name" "$area" "$from_rel")"
  to="$(resolve_storage_path "$name" "$area" "$to_rel")"
  [[ -e "$from" && ! -L "$from" ]] || die "File or folder not found."
  to_parent="$(dirname "$to")"
  [[ -d "$to_parent" && ! -L "$to_parent" ]] || die "Parent folder not found."
  [[ ! -e "$to" ]] || die "A file or folder with that name already exists."
  mv -- "$from" "$to"
  storage_stat "$name" "$owner" "$area" "$to_rel"
}

storage_copy() {
  local name="$1" owner="$2" area="$3" from_rel="$4" to_rel="$5" from to to_parent
  verify_storage "$name" "$owner"
  [[ -n "$from_rel" && -n "$to_rel" ]] || die "copy requires source and destination"
  from="$(resolve_storage_path "$name" "$area" "$from_rel")"
  to="$(resolve_storage_path "$name" "$area" "$to_rel")"
  [[ -e "$from" && ! -L "$from" ]] || die "File or folder not found."
  to_parent="$(dirname "$to")"
  [[ -d "$to_parent" && ! -L "$to_parent" ]] || die "Parent folder not found."
  [[ ! -e "$to" ]] || die "A file or folder with that name already exists."
  if [[ -d "$from" ]]; then
    cp -a -- "$from" "$to"
  else
    cp -- "$from" "$to"
  fi
  chown -R "$AGENT_UID:$AGENT_GID" "$to"
  storage_stat "$name" "$owner" "$area" "$to_rel"
}

create_container() {
  local name="$1" owner="$2" cpus="$3" memory_mb="$4" image="$5" engine_image root network network_identity ip mac
  valid_name "$name" && valid_owner "$owner" && valid_resources "$cpus" "$memory_mb" && valid_image "$image" || die "invalid create arguments"
  engine_image="$(podman_image "$image")"
  root="$(channel_root "$name")"
  network="$(ensure_network "$owner")"
  network_identity="$(ensure_network_identity "$name" "$owner" "$network")"
  read -r ip mac <<<"$network_identity"
  [[ -n "$ip" && -n "$mac" ]] || die "channel network identity was incomplete"
  "${PODMAN[@]}" create --name "$name" --hostname "$name" --network "$network" --ip "$ip" --mac-address "$mac" \
    --cpus "$cpus" --memory "${memory_mb}m" --pids-limit 4096 --systemd=always \
    --stop-signal SIGRTMIN+3 --stop-timeout 90 \
    --label com.1helm.managed=true --label "com.1helm.owner=$owner" --label "com.1helm.machine=$name" \
    --mount "type=bind,src=$root/workspace,dst=/workspace" \
    --mount "type=bind,src=$root/files,dst=/workspace/files" \
    --mount "type=bind,src=$root/home,dst=/home/agent" \
    --mount "type=bind,src=$root/var-lib-1helm,dst=/var/lib/1helm" \
    "$engine_image" >/dev/null
  verify_container "$name" "$owner"
}

start_container() {
  local name="$1" owner="$2" state network root network_ready container_ok=0 network_ok=0
  verify_container "$name" "$owner"
  root="$(channel_root "$name")"
  network_ready="$root/network-ready-v1"
  network="$(ensure_network "$owner")"
  # Re-assert egress on every start: Docker and host firewall reloads can drop
  # our FORWARD/NAT inserts after boot or package updates.
  if "${PODMAN[@]}" network exists "$network"; then ensure_guest_egress "$network"; fi
  state="$(container_state "$name")"
  # An update from the earlier aardvark-backed contract must restart a running
  # retained container once so Podman regenerates /etc/resolv.conf from the
  # now host-inherited network definition.
  if [[ "$state" == running && ! -f "$network_ready" ]]; then
    "${PODMAN[@]}" stop --time 90 "$name" >/dev/null
    state="stopped"
  fi
  if [[ "$state" != running ]]; then "${PODMAN[@]}" start "$name" >/dev/null; fi
  for _ in {1..100}; do
    # Podman can briefly fail name-based --user lookup while it reconstructs
    # its ephemeral runroot after a host reboot even though the persisted
    # image passwd database is intact.  These identities are pinned by the
    # installed runtime manifest and image contract, so use their numeric form
    # for the readiness probe and every subsequent exec boundary.
    if "${PODMAN[@]}" exec --user 0:0 "$name" /bin/sh -c \
        'test "$(cat /var/lib/1helm/owner)" = "$1" && test -d /workspace && test -d /home/agent' \
        1helm-start "$owner" >/dev/null 2>&1; then
      verify_container "$name" "$owner"
      container_ok=1
      break
    fi
    sleep 0.1
  done
  [[ "$container_ok" -eq 1 ]] || die "container did not pass its ownership and storage health check"
  if [[ ! -f "$network_ready" ]]; then
    for _ in {1..5}; do
      if timeout 7 "${PODMAN[@]}" exec --user "$AGENT_UID:$AGENT_GID" "$name" /usr/bin/python3 -c \
          'import socket; s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.close(); socket.getaddrinfo("example.com",443,type=socket.SOCK_STREAM); c=socket.create_connection(("example.com",443),3); c.close()' \
          >/dev/null 2>&1; then network_ok=1; break; fi
      sleep 0.2
    done
    [[ "$network_ok" -eq 1 ]] || die "container did not pass its network socket, public DNS, and TCP egress health check"
    printf '%s\n' 'host-dns-and-public-tcp-v1' >"$network_ready"
    chown root:root "$network_ready"
    chmod 0600 "$network_ready"
  fi
}

stop_container() {
  local name="$1" owner="$2" state
  verify_container "$name" "$owner"
  state="$(container_state "$name")"
  [[ "$state" == running ]] || return 0
  "${PODMAN[@]}" stop --time 90 "$name" >/dev/null
}

inspect_container() {
  local name="$1" owner="$2" raw
  if ! container_exists "$name"; then printf 'null\n'; return; fi
  verify_container "$name" "$owner"
  raw="$("${PODMAN[@]}" inspect --type container "$name")"
  python3 - "$raw" "$name" <<'PY'
import json, sys
row=json.loads(sys.argv[1])[0]
host=row.get("HostConfig") or {}
quota=int(host.get("CpuQuota") or 0)
period=int(host.get("CpuPeriod") or 100000)
cpus=max(1, round(quota/period)) if quota else 0
print(json.dumps({
  "id":sys.argv[2],
  "status":str((row.get("State") or {}).get("Status") or "unknown"),
  "cpus":cpus,
  "memory":int(host.get("Memory") or 0),
  "homeMount":"none",
  "image":str(row.get("ImageName") or row.get("Image") or ""),
}, separators=(",",":")))
PY
}

load_pinned_image() {
  local image="$1" engine_image expected actual
  valid_image "$image" || die "invalid image reference"
  engine_image="$(podman_image "$image")"
  if "${PODMAN[@]}" image exists "$engine_image"; then return; fi
  [[ -f "$IMAGE_ARCHIVE" && ! -L "$IMAGE_ARCHIVE" ]] || die "sealed channel image archive is missing: $IMAGE_ARCHIVE"
  [[ -f "$IMAGE_SHA256_FILE" && ! -L "$IMAGE_SHA256_FILE" ]] || die "sealed channel image digest file is missing: $IMAGE_SHA256_FILE"
  expected="$(tr -d '[:space:]' <"$IMAGE_SHA256_FILE")"
  [[ "$expected" =~ ^[a-f0-9]{64}$ ]] || die "sealed channel image digest is invalid"
  actual="$(sha256sum "$IMAGE_ARCHIVE" | awk '{print $1}')"
  [[ "$actual" == "$expected" ]] || die "sealed channel image digest does not match"
  # Customer hosts load a CI-built archive. They never apt against live mirrors.
  "${PODMAN[@]}" load --input "$IMAGE_ARCHIVE" >/dev/null
  if ! "${PODMAN[@]}" image exists "$engine_image"; then
    # oci-archive load may restore a different local name; retag the only loaded ref if needed.
    loaded="$("${PODMAN[@]}" images --format '{{.Repository}}:{{.Tag}}' | awk -F: '$1 ~ /1helm-channel-machine$/ {print; exit}')"
    [[ -n "$loaded" && "$loaded" != "<none>:<none>" ]] || die "sealed channel image did not load under a usable name"
    "${PODMAN[@]}" tag "$loaded" "$engine_image"
  fi
  "${PODMAN[@]}" image exists "$engine_image" || die "sealed channel image was not present after load"
}

build_image() {
  local image="$1" engine_image
  valid_image "$image" || die "invalid image reference"
  engine_image="$(podman_image "$image")"
  if "${PODMAN[@]}" image exists "$engine_image"; then return; fi
  if [[ -f "$IMAGE_ARCHIVE" && -f "$IMAGE_SHA256_FILE" ]]; then
    load_pinned_image "$image"
    return
  fi
  # Live Containerfile builds are development-only. Product Linux/Windows installs
  # ship the sealed archive and must never depend on customer-side apt mirrors.
  if [[ "${HELM_OCI_ALLOW_LIVE_BUILD:-}" == "1" ]]; then
    [[ -r "$CONTAINERFILE" ]] || die "installed OCI image recipe is missing"
    "${PODMAN[@]}" build --network=host --pull=missing \
      --build-arg "AGENT_UID=$AGENT_UID" --build-arg "AGENT_GID=$AGENT_GID" \
      --tag "$engine_image" --file "$CONTAINERFILE" "$(dirname "$CONTAINERFILE")"
    "${PODMAN[@]}" image exists "$engine_image" || die "OCI image did not exist after build"
    return
  fi
  die "sealed channel image archive is not installed; product hosts load a pinned image instead of building live"
}

copy_tree_from_container() {
  local temporary="$1" source="$2" destination="$3"
  install -d -o "$AGENT_UID" -g "$AGENT_GID" -m 0700 "$destination"
  if "${PODMAN[@]}" cp "$temporary:$source/." "$destination" >/dev/null 2>&1; then
    chown -R "$AGENT_UID:$AGENT_GID" "$destination"
  fi
}

backup_name_valid() {
  local name="$1" backup="$2"
  [[ "$backup" =~ ^${name}-[0-9]{13}-[a-f0-9]{12}\.tar$ ]]
}

backup_container() {
  local name="$1" owner="$2" temporary root stamp nonce backup destination digest
  verify_container "$name" "$owner"
  [[ "$(container_state "$name")" != running ]] || die "container must be stopped before backup"
  stamp="$(date +%s%3N)"
  nonce="$(printf '%s' "$name:$owner:$(date +%s%N):$$" | sha256sum | cut -c1-12)"
  backup="$name-$stamp-$nonce.tar"
  backup_name_valid "$name" "$backup" || die "could not create a safe backup identity"
  destination="$BACKUPS_ROOT/$backup"
  temporary="$(mktemp -d "$BACKUPS_ROOT/.backup-$name-XXXXXX")"
  trap '[[ -z "${temporary:-}" ]] || rm -rf -- "$temporary"' EXIT
  root="$(channel_root "$name")"
  "${PODMAN[@]}" export --output "$temporary/rootfs.tar" "$name"
  tar --numeric-owner --xattrs --acls -C "$root" -cf "$temporary/channel.tar" .
  "${PODMAN[@]}" inspect --type container "$name" >"$temporary/container.json"
  tar -C "$temporary" -cf "$destination.candidate" rootfs.tar channel.tar container.json
  chmod 0600 "$destination.candidate"
  mv -T "$destination.candidate" "$destination"
  digest="$(sha256sum "$destination" | awk '{print $1}')"
  printf '{"backup":"%s","sha256":"%s","path":"%s"}\n' "$backup" "$digest" "$destination"
  rm -rf -- "$temporary"
  trap - EXIT
}

list_backups() {
  local name="$1" owner="$2" root backup digest first=1
  valid_name "$name" && valid_owner "$owner" || die "invalid container identity"
  [[ "${name#1helm-}" == "$(owner_installation "$owner")-channel-$(owner_channel "$owner")" ]] || die "container name and owner do not match"
  root="$(channel_root "$name")"
  if [[ -e "$root/var-lib-1helm/owner" ]]; then
    [[ "$(tr -d '\r\n' <"$root/var-lib-1helm/owner")" == "$owner" ]] || die "ownership marker does not match"
  fi
  printf '['
  while IFS= read -r -d '' backup; do
    backup="${backup##*/}"
    backup_name_valid "$name" "$backup" || continue
    digest="$(sha256sum "$BACKUPS_ROOT/$backup" | awk '{print $1}')"
    [[ "$first" -eq 1 ]] || printf ','
    first=0
    printf '{"backup":"%s","sha256":"%s"}' "$backup" "$digest"
  done < <(find -P "$BACKUPS_ROOT" -maxdepth 1 -type f -name "$name-*.tar" -print0 | sort -zr)
  printf ']\n'
}

restore_container() {
  local name="$1" owner="$2" backup="$3" expected_digest="$4" archive digest temporary root metadata resources cpus memory_mb restored_image created=0
  valid_name "$name" && valid_owner "$owner" || die "invalid container identity"
  [[ "${name#1helm-}" == "$(owner_installation "$owner")-channel-$(owner_channel "$owner")" ]] || die "container name and owner do not match"
  backup_name_valid "$name" "$backup" || die "invalid backup identity"
  [[ "$expected_digest" =~ ^[a-f0-9]{64}$ ]] || die "invalid backup digest"
  archive="$BACKUPS_ROOT/$backup"
  [[ -f "$archive" && ! -L "$archive" ]] || die "backup does not exist"
  digest="$(sha256sum "$archive" | awk '{print $1}')"
  [[ "$digest" == "$expected_digest" ]] || die "backup digest does not match"
  ! container_exists "$name" || die "restore target container already exists"
  root="$(channel_root "$name")"
  [[ ! -e "$root" ]] || die "restore target storage already exists"
  temporary="$(mktemp -d "$BACKUPS_ROOT/.restore-$name-XXXXXX")"
  trap '[[ "${created:-0}" -eq 0 ]] || "${PODMAN[@]}" rm -f "$name" >/dev/null 2>&1 || true; [[ -z "${root:-}" || "$root" != "$CHANNELS_ROOT/"* ]] || rm -rf -- "$root"; [[ -z "${restored_image:-}" ]] || "${PODMAN[@]}" rmi "$(podman_image "$restored_image")" >/dev/null 2>&1 || true; [[ -z "${temporary:-}" ]] || rm -rf -- "$temporary"' EXIT
  metadata="$(tar -tf "$archive")"
  [[ "$metadata" == $'rootfs.tar\nchannel.tar\ncontainer.json' ]] || die "backup members do not match the OCI recovery contract"
  tar -C "$temporary" -xf "$archive"
  resources="$(python3 - "$temporary/container.json" "$name" "$owner" <<'PY'
import json, sys
rows=json.load(open(sys.argv[1], encoding="utf-8"))
if not isinstance(rows,list) or len(rows)!=1: raise SystemExit("backup container metadata is invalid")
row=rows[0]
labels=(row.get("Config") or {}).get("Labels") or {}
expected={"com.1helm.managed":"true","com.1helm.machine":sys.argv[2],"com.1helm.owner":sys.argv[3]}
if any(str(labels.get(k,"")) != v for k,v in expected.items()): raise SystemExit("backup ownership labels do not match")
host=row.get("HostConfig") or {}
quota=int(host.get("CpuQuota") or 0); period=int(host.get("CpuPeriod") or 100000)
cpus=max(1,min(8,round(quota/period))) if quota else 2
memory=max(1024,min(16384,round(int(host.get("Memory") or 2147483648)/1048576)))
print(cpus, memory)
PY
)" || die "backup container metadata could not be verified"
  read -r cpus memory_mb <<<"$resources"
  restored_image="local/1helm-channel-restored:${digest:0:20}"
  "${PODMAN[@]}" import --change 'CMD ["/sbin/init"]' --change 'STOPSIGNAL SIGRTMIN+3' --change 'ENV container=oci' "$temporary/rootfs.tar" "$(podman_image "$restored_image")" >/dev/null
  install -d -o root -g root -m 0700 "$temporary/channel"
  python3 - "$temporary/channel.tar" "$temporary/channel" <<'PY'
import os, sys, tarfile
archive, destination=sys.argv[1:]
with tarfile.open(archive, "r:") as source:
    members=source.getmembers()
    for member in members:
        normalized=os.path.normpath(member.name)
        if os.path.isabs(member.name) or normalized == ".." or normalized.startswith("../"):
            raise SystemExit("backup channel storage contains an unsafe path")
    source.extractall(destination, filter="data")
PY
  mv -T "$temporary/channel" "$root"
  chown root:root "$root"
  chmod 0711 "$root"
  verify_storage "$name" "$owner"
  for shared in "$root/workspace" "$root/files" "$root/home"; do
    chown -R "$AGENT_UID:$AGENT_GID" "$shared"
    grant_shared_access "$shared"
  done
  chown -R root:root "$root/var-lib-1helm"
  created=1
  create_container "$name" "$owner" "$cpus" "$memory_mb" "$restored_image"
  start_container "$name" "$owner"
  inspect_container "$name" "$owner"
  created=0
  rm -rf -- "$temporary"
  trap - EXIT
}

operation="${1:-}"
shift || true
ensure_roots
case "$operation" in
  version)
    (($# == 0)) || die "version takes no arguments"
    printf '%s\n' "$RUNTIME_VERSION"
    ;;
  ready)
    (($# == 0)) || die "ready takes no arguments"
    for command in find flock getfacl iptables podman python3 setfacl sha256sum stat tar timeout; do command -v "$command" >/dev/null || die "missing $command"; done
    [[ -r "$CONTAINERFILE" ]] || die "installed OCI image recipe is missing"
    "${PODMAN[@]}" info >/dev/null
    printf '{"ready":true,"version":"%s","engine":"podman"}\n' "$RUNTIME_VERSION"
    ;;
  image)
    (($# == 1)) || die "image requires a reference"
    build_image "$1"
    ;;
  image-status)
    (($# == 1)) || die "image-status requires a reference"
    valid_image "$1" || die "invalid image reference"
    engine_image="$(podman_image "$1")"
    if "${PODMAN[@]}" image exists "$engine_image"; then
      printf '{"exists":true,"image":"%s"}\n' "$1"
    else
      printf '{"exists":false,"image":"%s"}\n' "$1"
    fi
    ;;
  create)
    (($# == 5)) || die "create requires name, owner, CPUs, memory MiB, and image"
    ! container_exists "$1" || die "container already exists"
    storage_existed=0
    [[ -e "$(channel_root "$1")" ]] && storage_existed=1
    prepare_storage "$1" "$2"
    if ! create_container "$1" "$2" "$3" "$4" "$5"; then
      container_exists "$1" && "${PODMAN[@]}" rm -f "$1" >/dev/null 2>&1 || true
      if [[ "$storage_existed" -eq 0 ]]; then
        failed_root="$(channel_root "$1")"
        [[ "$failed_root" == "$CHANNELS_ROOT/$1" ]] || die "unsafe failed-create cleanup target"
        rm -rf -- "$failed_root"
      fi
      exit 1
    fi
    start_container "$1" "$2"
    ;;
  inspect)
    (($# == 2)) || die "inspect requires name and owner"
    inspect_container "$1" "$2"
    ;;
  list)
    (($# == 1)) || die "list requires an installation prefix"
    [[ "$1" =~ ^1helm-[a-f0-9]{16}-channel-$ ]] || die "invalid installation prefix"
    "${PODMAN[@]}" ps --all --format '{{.Names}}' --filter label=com.1helm.managed=true | awk -v prefix="$1" 'index($0,prefix)==1 {print}' | python3 -c 'import json,sys; print(json.dumps([line.strip() for line in sys.stdin if line.strip()]))'
    ;;
  start)
    (($# == 2)) || die "start requires name and owner"
    start_container "$1" "$2"
    ;;
  stop)
    (($# == 2)) || die "stop requires name and owner"
    stop_container "$1" "$2"
    ;;
  set)
    (($# == 4)) || die "set requires name, owner, CPUs, and memory MiB"
    verify_container "$1" "$2"
    valid_resources "$3" "$4" || die "invalid resource limits"
    "${PODMAN[@]}" update --cpus "$3" --memory "${4}m" "$1" >/dev/null
    ;;
  exec)
    (($# >= 6)) || die "exec requires name, owner, user, workdir, [--env NAME=VALUE]..., --, and command"
    name="$1"; owner="$2"; user="$3"; workdir="$4"; shift 4
    [[ "$user" == agent || "$user" == root ]] || die "invalid exec user"
    [[ "$workdir" == / || "$workdir" == /workspace || "$workdir" == /home/agent ]] || die "invalid exec workdir"
    # Forwarded identity/environment pairs from the server (HOME/USER/LOGNAME).
    exec_env=()
    while [[ "${1:-}" == --env ]]; do
      [[ "$#" -ge 2 && "$2" == *=* && "$2" != *= ]] || die "--env requires NAME=VALUE"
      exec_env+=("$1" "$2")
      shift 2
    done
    [[ "${1:-}" == -- ]] || die "missing exec separator"; shift
    (($# > 0)) || die "missing exec command"
    start_container "$name" "$owner"
    if [[ "$user" == root ]]; then numeric_user="0:0"; else numeric_user="$AGENT_UID:$AGENT_GID"; fi
    exec "${PODMAN[@]}" exec --interactive --user "$numeric_user" --workdir "$workdir" ${exec_env[@]+"${exec_env[@]}"} "$name" "$@"
    ;;
  terminal)
    (($# == 2)) || die "terminal requires name and owner"
    start_container "$1" "$2"
    # Terminals always run as the agent user; give them the same explicit
    # identity environment as exec so login/profile wiring behaves identically.
    exec "${PODMAN[@]}" exec --interactive --tty --user "$AGENT_UID:$AGENT_GID" --workdir /workspace \
      --env TERM=xterm-256color --env HOME=/home/agent --env USER=agent --env LOGNAME=agent "$1" /bin/bash -l
    ;;
  backup)
    (($# == 2)) || die "backup requires name and owner"
    backup_container "$1" "$2"
    ;;
  backups)
    (($# == 2)) || die "backups requires name and owner"
    list_backups "$1" "$2"
    ;;
  restore)
    (($# == 4)) || die "restore requires name, owner, backup, and SHA-256"
    restore_container "$1" "$2" "$3" "$4"
    ;;
  delete)
    (($# == 2)) || die "delete requires name and owner"
    verify_container "$1" "$2"
    stop_container "$1" "$2"
    "${PODMAN[@]}" rm "$1" >/dev/null
    root="$(channel_root "$1")"
    [[ "$root" == "$CHANNELS_ROOT/$1" ]] || die "unsafe channel cleanup target"
    rm -rf -- "$root"
    ;;
  # Host Files/Cowork bridge: Windows cannot use \\wsl.localhost when interop is
  # disabled (isolation contract). These ops read/write channel storage as root
  # under the helper's ownership checks, never via the Windows 9p share.
  storage-list)
    (($# == 3 || $# == 4)) || die "storage-list requires name, owner, area [, relative path]"
    storage_list "$1" "$2" "$3" "${4:-}"
    ;;
  storage-stat)
    (($# == 3 || $# == 4)) || die "storage-stat requires name, owner, area [, relative path]"
    storage_stat "$1" "$2" "$3" "${4:-}"
    ;;
  storage-mkdir)
    (($# == 4)) || die "storage-mkdir requires name, owner, area, relative path"
    storage_mkdir "$1" "$2" "$3" "$4"
    ;;
  storage-write)
    (($# == 4 || $# == 5)) || die "storage-write requires name, owner, area, relative path [, create|overwrite]"
    storage_write "$1" "$2" "$3" "$4" "${5:-overwrite}"
    ;;
  storage-read)
    (($# == 4)) || die "storage-read requires name, owner, area, relative path"
    storage_read "$1" "$2" "$3" "$4"
    ;;
  storage-rm)
    (($# == 4 || $# == 5)) || die "storage-rm requires name, owner, area, relative path [, 0|1 recursive]"
    storage_rm "$1" "$2" "$3" "$4" "${5:-0}"
    ;;
  storage-rename)
    (($# == 5)) || die "storage-rename requires name, owner, area, from, to"
    storage_rename "$1" "$2" "$3" "$4" "$5"
    ;;
  storage-copy)
    (($# == 5)) || die "storage-copy requires name, owner, area, from, to"
    storage_copy "$1" "$2" "$3" "$4" "$5"
    ;;
  *) die "unsupported operation" ;;
esac
