#!/bin/sh
# semurg-machine -- THE SHELL TWIN of the engine's core_pin::machine() (hardware-dynamic, desktop-c4 [15f33d] 2026-10-12; the founder: "all
# dynamically scale based on the hardware semurg is deployed on"; Comms HARDWARE_DYNAMIC_AUDIT_20261012.md sec 5). The boot shell runs BEFORE
# the engine loads, so it reads the SAME /proc + /sys by the SAME rules; the engine's plant (apps/substrate_core/test/machine_test.exs) runs
# this and compares it with SubstrateCore.Machine on the same box. SOURCED after semurg-cpu-partition (whose semurg_allowed_cpus is THE ONE
# reader of the cpus this node may use), or RUN (`sh semurg-machine`: it finds semurg-cpu-partition beside itself and prints the lines).
#
# `semurg_machine` prints KEY=VALUE lines (no spaces in any value, so `eval "$(semurg_machine)"` is safe):
#   THREADS          the hardware threads this node may run at once: |the cgroup's cpus n online|, min the cgroup CPU quota, narrowed only
#                    by an override
#   THREADS_DERIVED  the same before any override
#   ONLINE           the kernel's online cpu count
#   CORES            distinct (physical_package_id, core_id) over the allowed cpus (a cpu with no topology is its own core), never above
#                    THREADS, narrowed only by SEMURG_WIDTH_CORES
#   L3_DOMAINS       distinct L3 domains (the first cpu of cache/index3/shared_cpu_list) over the allowed cpus, at least 1
#   QUOTA            ceil(quota / period), the minimum over the cgroup and its ancestors (v2 cpu.max, else v1 cfs), or "unlimited"
#   ALLOWED          the allowed cpus as a cpu-list ("0-3,8-11")
#   AFFINITY         this shell's affinity mask (a wrapper taskset, the partition's confinement): REPORTED, never a width
#   OVERRIDE         NAME=used/derived for each override applied (comma separated), or empty
# NEVER nproc, never an affinity mask, for a width. Overrides: SEMURG_WIDTH_THREADS (aliases SEMURG_FAN_CORES, SEMURG_PHYS: the first one
# SET wins), SEMURG_WIDTH_CORES; they only narrow (above the derived width keeps the derived width; a cpu cannot be invented). A malformed
# override, or no cpu list readable at all, refuses BY NAME with rc 78 and prints no width (never a guessed number).
# SEAMS (plants only; the R1 boot-width plant plants a narrower cgroup with them): SEMURG_MACHINE_SYS_ROOT (/sys),
# SEMURG_MACHINE_CGROUP_ROOT (/sys/fs/cgroup), SEMURG_MACHINE_SELF_CGROUP (/proc/self/cgroup).
# POSIX sh + awk + /proc + /sys; no literal cpu anywhere.

semurg_cpu_quota() { # prints the cgroup CPU-quota ceiling, or nothing (unlimited); the engine's quota_ceiling_from, the same files in the same order
  local cgr self cg p f best v2 path m
  cgr="${SEMURG_MACHINE_CGROUP_ROOT:-/sys/fs/cgroup}"; self="${SEMURG_MACHINE_SELF_CGROUP:-/proc/self/cgroup}"
  best=""; v2=0
  # v2: "0::<path>", each ancestor, then the root (a quota on a parent slice binds the child)
  cg="$(sed -n 's/^0:://p' "$self" 2>/dev/null | head -1)"
  p="${cg%/}"
  while :; do
    f="${cgr}${p}/cpu.max"
    if [ -r "$f" ]; then
      v2=1
      best="$(awk -v best="$best" '{ if ($1 != "max") { per = ($2 == "" ? 100000 : $2); if (per > 0) { c = int(($1 + per - 1) / per); if (c < 1) c = 1; if (best == "" || c < best) best = c } } } END { print best }' "$f")"
    fi
    [ -z "$p" ] && break
    p="${p%/*}"
  done
  [ "$v2" = 1 ] && { printf '%s' "$best"; return; }
  # v1: the line whose controllers name "cpu", each ancestor, the root, under both mount names
  path="$(awk -F: '$2 ~ /(^|,)cpu(,|$)/ {print $3; exit}' "$self" 2>/dev/null)"
  for m in "${cgr}/cpu" "${cgr}/cpu,cpuacct"; do
    p="${path%/}"
    while :; do
      if [ -r "${m}${p}/cpu.cfs_quota_us" ] && [ -r "${m}${p}/cpu.cfs_period_us" ]; then
        best="$(printf '%s %s\n' "$(cat "${m}${p}/cpu.cfs_quota_us")" "$(cat "${m}${p}/cpu.cfs_period_us")" | awk -v best="$best" '{ if ($1 > 0 && $2 > 0) { c = int(($1 + $2 - 1) / $2); if (c < 1) c = 1; if (best == "" || c < best) best = c } } END { print best }')"
      fi
      [ -z "$p" ] && break
      p="${p%/*}"
    done
  done
  printf '%s' "$best"
}

semurg_cpu_list_text() { # one cpu per line (ascending) -> "0-3,8-11"
  awk 'NF { if (n && $1 == last + 1) { last = $1; next } if (n) out = out (out == "" ? "" : ",") (first == last ? first : first "-" last); first = last = $1; n = 1 }
       END { if (n) out = out (out == "" ? "" : ",") (first == last ? first : first "-" last); print out }'
}

semurg_machine() { # the KEY=VALUE lines above; rc 78 by name on a malformed override or nothing readable
  local sysr allowed n online quota threads cores l3 name v used ov used_t used_c
  command -v semurg_allowed_cpus >/dev/null 2>&1 || { echo "semurg-machine: semurg_allowed_cpus is not defined: source semurg-cpu-partition first [refused:machine_helper_missing]" >&2; return 78; }
  sysr="${SEMURG_MACHINE_SYS_ROOT:-/sys}"
  allowed="$(semurg_allowed_cpus)"
  [ -n "$allowed" ] || { echo "semurg-machine: no cpu list readable (the cgroup's cpuset nor ${sysr}/devices/system/cpu/online) [refused:machine_unreadable]" >&2; return 78; }
  n="$(printf '%s\n' "$allowed" | wc -l | tr -d ' ')"
  online="$(semurg_cpu_list "$(cat "${sysr}/devices/system/cpu/online" 2>/dev/null)" | wc -l | tr -d ' ')"
  [ "$online" -ge 1 ] 2>/dev/null || online="$n"
  quota="$(semurg_cpu_quota)"
  threads="$n"; [ -n "$quota" ] && [ "$quota" -lt "$threads" ] && threads="$quota"
  # cores + L3 domains over the allowed cpus (a cpu with no /sys topology is its own core; one with no L3 list is in no domain)
  set -- $(for c in $allowed; do
             t="${sysr}/devices/system/cpu/cpu$c"
             pkg="$(cat "$t/topology/physical_package_id" 2>/dev/null)"; core="$(cat "$t/topology/core_id" 2>/dev/null)"
             if [ -n "$pkg" ] && [ -n "$core" ]; then k="$pkg.$core"; else k="cpu$c"; fi
             d="$(semurg_cpu_list "$(cat "$t/cache/index3/shared_cpu_list" 2>/dev/null)" | head -1)"
             printf '%s %s\n' "$k" "${d:--}"
           done | awk '{ cores[$1] = 1; if ($2 != "-") dom[$2] = 1 } END { nc = 0; for (k in cores) nc++; nd = 0; for (k in dom) nd++; if (nd < 1) nd = 1; print nc, nd }')
  cores="$1"; l3="$2"
  [ "$cores" -gt "$threads" ] && cores="$threads"
  ov=""; used_t="$threads"; used_c="$cores"
  for name in SEMURG_WIDTH_THREADS SEMURG_FAN_CORES SEMURG_PHYS; do
    eval "[ -n \"\${$name+x}\" ]" || continue
    eval "v=\"\${$name}\""
    case "$v" in ''|*[!0-9]*) echo "semurg-machine: ${name}=${v} is not a width (an integer >= 1); unset it or give a count [refused:machine_override]" >&2; return 78 ;; esac
    [ "$v" -ge 1 ] || { echo "semurg-machine: ${name}=${v} is not a width (an integer >= 1); unset it or give a count [refused:machine_override]" >&2; return 78; }
    used="$v"; [ "$used" -gt "$threads" ] && used="$threads"
    used_t="$used"; ov="${name}=${used}/${threads}"
    break
  done
  if [ -n "${SEMURG_WIDTH_CORES+x}" ]; then
    v="$SEMURG_WIDTH_CORES"
    case "$v" in ''|*[!0-9]*) echo "semurg-machine: SEMURG_WIDTH_CORES=${v} is not a width (an integer >= 1); unset it or give a count [refused:machine_override]" >&2; return 78 ;; esac
    [ "$v" -ge 1 ] || { echo "semurg-machine: SEMURG_WIDTH_CORES=${v} is not a width (an integer >= 1); unset it or give a count [refused:machine_override]" >&2; return 78; }
    used="$v"; [ "$used" -gt "$cores" ] && used="$cores"
    used_c="$used"; ov="${ov}${ov:+,}SEMURG_WIDTH_CORES=${used}/${cores}"
  fi
  [ "$used_c" -gt "$used_t" ] && used_c="$used_t"
  printf 'THREADS=%s\nTHREADS_DERIVED=%s\nONLINE=%s\nCORES=%s\nL3_DOMAINS=%s\nQUOTA=%s\nALLOWED=%s\nAFFINITY=%s\nOVERRIDE=%s\n' \
    "$used_t" "$threads" "$online" "$used_c" "$l3" "${quota:-unlimited}" \
    "$(printf '%s\n' "$allowed" | semurg_cpu_list_text)" \
    "$(taskset -pc $$ 2>/dev/null | sed 's/.*: //')" "$ov"
}

# RUN (not sourced): load the one cpu reader from beside this file and print the lines
case "${0##*/}" in
  semurg-machine)
    command -v semurg_allowed_cpus >/dev/null 2>&1 || . "$(dirname "$0")/semurg-cpu-partition"
    semurg_machine ;;
esac
