#!/bin/sh
# Copyright (c) 2026 Jiaxing Hu <gahing@gahingwoo.com>
# SPDX-License-Identifier: GPL-2.0
# `charsiu ps`
#
# There is no daemon holding models in memory, so this is not ollama's ps and
# does not pretend to be. It answers the question people actually ask it here:
# is the NPU busy, and who has it.
set -eu
printf '%-8s %-9s %s\n' PID STATE WHAT
found=0
for p in /proc/[0-9]*; do
	[ -r "$p/cmdline" ] || continue
	# 2>/dev/null MUST COME BEFORE THE INPUT REDIRECT. Redirections are
	# processed left to right, so with it after, the shell reports the
	# failed open on a stderr that is still the terminal -- and a process
	# exiting between the glob and this read is normal, not exceptional.
	c=$(tr '\0' ' ' 2>/dev/null < "$p/cmdline") || continue
	case "$c" in
	*charsiu_run*|*charsiu-runner*)
		found=1
		printf '%-8s %-9s %s\n' "${p#/proc/}" \
			"$(awk '/^State:/{print $2}' "$p/status" 2>/dev/null)" \
			"$(echo "$c" | cut -c1-60)" ;;
	esac
done
[ "$found" = 0 ] && echo "(nothing running)"
echo
for d in /sys/bus/platform/devices/*.npu; do
	[ -d "$d/power" ] || continue
	printf '  %-16s %s\n' "$(basename "$d")" "$(cat "$d/power/runtime_status" 2>/dev/null)"
done
for r in /sys/class/regulator/regulator.*; do
	[ -r "$r/name" ] || continue
	[ "$(cat "$r/name")" = vdd_npu_s0 ] || continue
	printf '  %-16s %s\n' "npu rail" "$(cat "$r/state" 2>/dev/null)"
done
exit 0
