#!/usr/bin/env bash
#
# Run a command with no or limited output but returns the error code.
#
# Set $OUTPUT environment variable to control what is seen.
#
# Example:
#   No output by default. Exit code is passed through.
#     $ bin/run sudo apt-get install badpackage || echo "Didn't work!"
#
#   To only show stdErr, set OUTPUT=err
#     $ OUTPUT=err bin/run-quiet sudo apt-get install x || echo "Our call to apt-get install failed."
#     Running sudo apt-get install x ...
#     E: Unable to locate package x
#     Our call to apt-get install failed.
#
#  To show all output, set OUTPUT=all.
#
#     $ env OUTPUT=all bin/run-quiet sudo apt-get install x
#     Running sudo apt-get install x ...
#     Reading package lists... Done
#     Building dependency tree
#     Reading state information... Done
#     E: Unable to locate package x
#

runQuiet() {
    echo "Running $COMMAND ..."

    # If $OUTPUT=out, hide errors.
    if [ "${OUTPUT}" == "out" ]; then
      $COMMAND 2> /dev/null

    # If $OUTPUT=err, print only errors
    elif [ "${OUTPUT}" == "err" ]; then
      $COMMAND > /dev/null

    # If $OUTPUT=all, just print
    elif [ "${OUTPUT}" == "all" ]; then
      $COMMAND

    # Otherwise, hide output and errors
    else
      $COMMAND > /dev/null 2>&1
    fi

    exit $?
}

set -e
COMMAND=${@}
runQuiet
