#!/bin/bash
#
# Steven Maresca
# lightyear4 @t gmail.com
#
# Warn: a wrapper script that highlights stderr for 
# color-capable bourne shells
#
# start script

# Color to use for highlighting stderr.
# See bash manual for additional color codes
# default color = red, which = "\033[1;31m"

# Generic color that effectively means 
# "return to original color"="\033[0m"

if [ $# -lt 1 ] 
then
	# If the number of arguments passed to Warn is less than 1,
	# (i.e. Warn was executed without arguments), then echo 
	# information about the script, plus usage example.
	echo " "
	echo "Warn is a shell script that outputs stderr in red to"
	echo "help differentiate it from stdout (which remains"
	echo "its normal color). Note that this script will only"
	echo "work properly in a bourne-compatible shell that"
	echo "supports the usage of color in the console."
	echo " "
	echo "----------------------------------------------------"
	echo " "
	echo "Usage: $0 commandtorun arg1 arg2 argN"
	echo " "
	exit 1
else
	# pulls the command-to-run from $*, the shell variable
	# which contains the string of arguments passed to the
	# original command. In this case, its what youre trying
	# to run with stderr highlighting.
	export RUNCOMMAND="$*" 

	# creates a custom file descriptor that preserves stdout
	exec 3>&1

	# appends command-to-run plus all of its arguments
	# to the redirection that does the magic. 
	#
	# 2>&1 redirects stderr and stdout through the custom
	# file descriptor via >&3 which outputs stdout to the 
	# console. The custom descriptor is closed with 3>&- and
	# allows stderr to continue to be redrected through the pipe
	$RUNCOMMAND 2>&1 >&3 3>&- | \
	#
	# Note the "\" at the end of the original line; it just 
	# allows me to split up the command and pipe across a line or
	# two.
	# this awk command takes stdin from the pipe, and prints
	# the same line of input ($0) prepended with the red color code
	# and appended with the return-to-original color code.
	# 3>&- closes the custom descriptor for this command 
	awk '{print "\033[1;31m"$0"\033[0m"}' 3>&-
	
	# close custom descriptor for the script
	exec 3>&-
fi

# end script
