#!/bin/sh
# Verify that iotop-c respects the requested iteration count
# and exits promptly in batch mode.

set -eu

cleanup() {
    rm -f "$out" "$err" "$filtered_err"
}
trap cleanup EXIT

# Remove the known iotop-c warning about task_delayacct being disabled.
# All other stderr output is preserved and should be treated as errors.
filter_stderr() {
    sed '/task_delayacct is 0/d'
}

out=$(mktemp)
err=$(mktemp)
filtered_err=$(mktemp)

iteration_count=3

iotop-c -b --iter "$iteration_count" >"$out" 2>"$err" || true
filter_stderr <"$err" >"$filtered_err"

[ ! -s "$filtered_err" ]

# Count how many times the header appears
count="$(grep -c "Total DISK READ" "$out" || true)"

if [ "$count" -ne "$iteration_count" ]; then
    echo "ERROR: Expected $iteration_count headers, but found $count" >&2
    exit 1
fi
