#!/bin/sh
#
# io - summarize I/O resources used by the command
# I/O version of time command and outputs I/O resources used by the command
#
# ---
# source: https://github.com/ko1nksm/io

# shellcheck disable=SC2249

set -eu

IFS=$(printf '\n\t') \
  && TAB=${IFS#?} LF=${IFS%?} \
  && IFS=" ${TAB}${LF}"

case "$1" in
  -h | --help)
    printf '%s' "\
Usage: io [-h | --help] command [arguments]...

Reads from storage are not accurate unless the cache is cleared.
The environment variables IOCLEANUP and IOWARMUP can be used
to specify the commands to be used for cleanup and warnup.

e.g.
  base64 -w 999 /dev/urandom | head -n 1000000 >data.txt

  export IOCLEANUP='sudo sh -c \"echo 1 >/proc/sys/vm/drop_caches\"'
  export IOWARMUP='sort --version; cat --version'

  io bash -c 'time sort data.txt >/tmp/output.txt'
  io bash -c 'time cat data.txt | sort >/tmp/output.txt'
"
    exit 0
    ;;
esac

if [ ! -e "/proc/$$/io" ]; then
  printf '%s\n' "io: Not supported. The procfs (/proc/<PID>/io) is required."
  exit 1
fi

if [ -n "${IOCLEANUP+x}" ]; then
  if [ -n "${IOCLEANUP}" ]; then
    printf '%s\n' "io: cleanup: ${IOCLEANUP}"
    eval "${IOCLEANUP}"
  fi
else
  printf '%s\n' "io: The environment variables IOCLEANUP and IOWARMUP \
can be used to manage the cache."
fi >&2

if [ -n "${IOWARMUP:-}" ]; then
  printf '%s\n' "io: warmup: ${IOWARMUP}" >&2
  eval "${IOWARMUP}" >/dev/null 2>&1
fi

while IFS="${IFS}:" read -r name value; do
  case "${name}" in
    *[!a-zA-Z0-9_]*) continue ;;
  esac
  case "${value}" in
    *[!0-9]*) continue ;;
  esac
  eval "io_${name}=\$value"
done </proc/$$/io

"$@" && ex=0 || ex="$?"

echo >&2
while IFS="${IFS}:" read -r name value; do
  case "${name}" in
    *[!a-zA-Z0-9_]*) continue ;;
  esac
  case "${value}" in
    *[!0-9]*) continue ;;
  esac
  # shellcheck disable=SC2086,SC1102,SC2312
  echo "${name}: $((value - io_${name}))"
done </proc/$$/io >&2

exit "${ex}"
