#!/bin/sh
# nproc - fallback 'nproc' util for coreutils < 8.0

# TODO: Windows
#    Cygwin: ?
#    MinGW: https://lists.gnu.org/archive/html/bug-gnulib/2009-10/msg00168.html
#    http://stackoverflow.com/questions/9996935/how-to-call-wmi-using-mingw

case `uname` in
Linux)
	# Linux:
	#    _NPROCESSORS_CONF -- logical processors detected
	#    _NPROCESSORS_ONLN -- logical processors online
	#    (both access /sys/devices/system/cpu)
	# Also, interesting note:
	# https://github.com/dotnet/coreclr/commit/fe4bbc88babb3b01418c82540f3c716696e20fd1
	#     > `getconf _NPROCESSORS_ONLN` provides the number of cores available to
	#     > the OS scheduler, while `nproc` provides the number of cores available
	#     > to `nproc` itself.
	exec getconf _NPROCESSORS_ONLN
	;;
FreeBSD|NetBSD|OpenBSD)
	# OpenBSD:
	# http://man.openbsd.org/OpenBSD-current/man3/sysctl.3
	#    hw.ncpu -- CPUs in use (active)
	#    hw.ncpufound -- total CPUs
	exec /sbin/sysctl -n hw.ncpu
	;;
Darwin)
	# https://lists.apple.com/archives/darwin-dev/2007/Jun/msg00088.html
	#    hw.ncpu -- "consider it to be deprecated"
	#    hw.physicalcpu -- physical processors installed
	#    hw.availcpu -- logical processors online
	# https://lists.apple.com/archives/darwin-dev/2007/Jun/msg00078.html
	#   "activecpu is the correct name; the manifest constant name
	#    was not changed because people have existing code that has
	#    to compile vs. the MIB version of the call."
	exec /usr/sbin/sysctl -n hw.activecpu
	;;
SunOS)
	# https://docs.oracle.com/cd/E23824_01/html/821-1462/psrinfo-1m.html
	#    psrinfo -p -- physical processors
	# TODO: strip whitespace?
	exec /usr/sbin/psrinfo -p
	;;
*)
	echo "$0: unsupported OS '`uname`'" >&2
	echo 1
	;;
esac
