#!/bin/sh

# This file is sourced by both Dev full remote source-build entrypoints. The
# caller provides ssh_shell, remote_quote, service, and
# remote_build_started_epoch.

classify_remote_exit_137() {
  service_q=$(remote_quote "$service")
  since_q=$(remote_quote "@$remote_build_started_epoch")
  classification=$(
    ssh_shell "if command -v journalctl >/dev/null 2>&1 && journalctl -k --since $since_q --no-pager 2>/dev/null | grep -Eiq 'out of memory|oom-kill|killed process'; then printf host-oom; elif command -v kubectl >/dev/null 2>&1 && kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.name}{\" \"}{range .status.containerStatuses[*]}{.name}{\"=\"}{.lastState.terminated.reason}{\" \"}{end}{\"\\n\"}{end}' 2>/dev/null | grep -F $service_q | grep -q OOMKilled; then printf pod-oom; elif docker ps -aq --filter name=$service_q 2>/dev/null | xargs -r docker inspect --format '{{.Name}} {{.State.OOMKilled}}' 2>/dev/null | grep -Eq ' true$'; then printf container-oom; else printf unknown-sigkill; fi" \
      2>/dev/null || printf unknown-sigkill
  )
  printf '%s\n' "[cp9 persona build] $service: exit 137 classification=$classification (host-oom requires recent kernel evidence; pod/container OOM requires service-scoped OOMKilled evidence; otherwise remains unknown)" >&2
}
