#!/usr/bin/env bash
#  SPDX-License-Identifier: BSD-3-Clause
#  Copyright (C) 2023 Intel Corporation
#  All rights reserved.

shopt -s nullglob extglob

pmdir=$(readlink -f "$(dirname "$0")")
rootdir=$(readlink -f "$pmdir/../../../")
source "$rootdir/test/scheduler/common.sh"
source "$pmdir/common"

help() {
	cat <<- HELP

		Usage: $0 [-h] [-c count] [-d dir] [-l] [-p prefix] [cpu0 cpu1 ...]

		-h - Print this message.
		-c - Execute count times. 0 is the default and it means to run
		     indefinitely.
		-d - Directory where results should be saved. Default is /tmp.
		-l - Save output of the script to a log file (dir/${0##*/}.pm.log).
		-p - Add prefix to saved files.
		-t - How long to wait before each load read. Default is 1s.

		cpu - Valid cpu id (e.g. 0) to monitor.

		When started, ${0##*/} will enter loop to continuously monitor cpu
		load. Each iteration will be logged to stderr and a log file
		(dir/${0##*/}.pm.log).

	HELP
}

cleanup() {
	rm_pm_pid
}

# get_cpu_time() uses these, so put some stubs in place
xtrace_disable() { :; }
xtrace_restore() { :; }

_get_cpu_time() {
	get_cpu_time "$@"
}

count=0
interval=1
log_to_file=no
prefix=""

while getopts c:d:hlp:t: opt; do
	case "$opt" in
		c) count=$OPTARG ;;
		d) PM_OUTPUTDIR=$OPTARG ;;
		h)
			help
			exit 0
			;;
		l) log_to_file=yes ;;
		p) prefix=$OPTARG ;;
		t) interval=$OPTARG ;;
		*) ;;
	esac
done
shift $((OPTIND - 1))

declare -r log_file=${prefix:+${prefix}_}${0##*/}.pm.log

mkdir -p "$PM_OUTPUTDIR"
if [[ $log_to_file == yes ]]; then
	printf 'Redirecting to %s\n' "$PM_OUTPUTDIR/$log_file" >&2
	exec > "$PM_OUTPUTDIR/$log_file" 2>&1
fi

cpus=("$@")
((${#cpus[@]} > 0)) || cpus=($(get_online_cpus))

save_pm_pid
trap 'cleanup' EXIT
trap 'retag' USR1

_get_cpu_time "$count" "" 1 "$interval" "${cpus[@]}"
