#!/usr/bin/env bash
#
# process-output - prints output -both stdout and stderr- of a running process
#
# note: on macos you have to disable dtrace(1) SIP restriction with
#       $ csrutil enable --without dtrace

# shellcheck disable=SC3044

set -eu

# set pipefail if it works in a subshell, disregard if unsupported

# check pipefail support in a subshell, disregard if unsupported
(shopt -s pipefail 2>/dev/null) && shopt -s pipefail
(shopt -s nullglob 2>/dev/null) && shopt -s nullglob
(shopt -s inherit_errexit 2>/dev/null) && shopt -s inherit_errexit

if [ "$#" -eq 0 ]; then
  echo "Invalid usage. Correct usage: $(basename "$0") <pid>" >&2
  exit 1
fi

pid="$1"
if uname | grep -q Darwin; then
  sudo dtrace -p "${pid}" -qn '
      syscall::write*:entry
      /pid == $target && (arg0 == 1 || arg0 == 2)/ {
        printf("%s", copyinstr(arg1, arg2));
      }
    '
else
  strace="$(command strace)"
  sudo "${strace}" \
    --attach "${pid}" --follow-forks \
    --string-limit 9999999 \
    --signal '!all' --quiet=attach,exit \
    --trace=write --trace-fds=0,1,2
fi
