#!/bin/sh

# Run a command stored in a file and:
#
# 1. exit with its exit status code
# 2. stream its stdout output to a file
# 3. stream its stderr output to a file
# 4. optionally stream both stdout and stderr to /dev/stdout and /dev/stderr
#
# Usage:
#
#     $0 <COMMAND_FILE> <STDOUT_FILE> <STDERR_FILE> [1]

COMMAND_FILE="${1}"
STDOUT_FILE="${2}"
STDERR_FILE="${3}"
VERBOSE="${4}"
STDOUT_PIPE="${STDOUT_FILE}.pipe"
STDERR_PIPE="${STDERR_FILE}.pipe"

mkfifo "${STDOUT_PIPE}"
mkfifo "${STDERR_PIPE}"

# normally i thought to store the redirect destination ("/dev/null" when quiet
# and "/dev/std{out,err}" otherwise) in a variable then just use `> "${DEV}"`
# but apparently in some situations /dev/std{out,err} aren't available (namely,
# when run through lerna) so the if statement below is the safer bet:
if [ "${VERBOSE}" -eq 1 ]; then
  tee "${STDOUT_FILE}" < "${STDOUT_PIPE}" &
  tee "${STDERR_FILE}" < "${STDERR_PIPE}" &
else
  tee "${STDOUT_FILE}" < "${STDOUT_PIPE}" > /dev/null &
  tee "${STDERR_FILE}" < "${STDERR_PIPE}" > /dev/null &
fi

. "${COMMAND_FILE}" 1>"${STDOUT_PIPE}" 2>"${STDERR_PIPE}"

EXIT_CODE=$?

rm "${STDOUT_PIPE}"
rm "${STDERR_PIPE}"

exit $EXIT_CODE

