#!/data/data/com.termux/files/usr/bin/sh
#
#    cpu_usage: percentage of cpu time spent busy
#
#    Copyright (C) 2026 Dustin Kirkland
#
#    Authors: Dustin Kirkland <kirkland@byobu.org>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, version 3 of the License.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
__cpu_usage_detail() {
	[ -r /proc/stat ] && grep "^cpu" /proc/stat
}

__cpu_usage() {
	# Busy share of all cpu time since the previous run, from the
	# /proc/stat counters (user nice system idle iowait irq softirq
	# steal). Debian: #566255
	[ -r /proc/stat ] || return
	local cache="$BYOBU_RUN_DIR/cache.$BYOBU_BACKEND/cpu_usage.last"
	local cpu user nice system idle iowait irq softirq steal rest
	local total idle_all t0=0 i0=0 dt di pct
	read cpu user nice system idle iowait irq softirq steal rest < /proc/stat
	[ "$cpu" = "cpu" ] || return
	total=$((${user:-0} + ${nice:-0} + ${system:-0} + ${idle:-0} + ${iowait:-0} + ${irq:-0} + ${softirq:-0} + ${steal:-0}))
	idle_all=$((${idle:-0} + ${iowait:-0}))
	[ -r "$cache" ] && read t0 i0 < "$cache"
	printf "%s %s\n" "$total" "$idle_all" > "$cache"
	dt=$(($total - ${t0:-0}))
	di=$(($idle_all - ${i0:-0}))
	# Nothing to compare against on the first run (or after a counter reset)
	[ "${t0:-0}" -gt 0 ] && [ "$dt" -gt 0 ] && [ "$di" -ge 0 ] || return
	pct=$(((100 * ($dt - $di) + $dt / 2) / $dt))
	color b c W; printf "%s" "$pct"; color -; color c W; printf "%s" "$PCT"; color --
}

# vi: syntax=sh ts=4 noexpandtab
