#!/bin/sh
# Copyright 2010 - 2019 FARGOS Development, LLC
# Output colored text using ANSI escape codes
# $Id$
outputLine=""
boldState=""
fgSel="3" # assume foreground color
lastColorState=""
text=""
lastText=""
terminalType="${TERM}"
if test ! -t 1
then
	case "X${FORCE_COLOR}" in
	X | X0)
		terminalType="NONE"
		;;
	X1)
		;;
	X2)
		terminalType="xterm"
		;;
	esac
fi

if test $# -eq 1
then # only 1 argument
	case "${1}" in
	-h | -help | --help)
		printf "usage: %s [{--bold | --normal | --underline | --blink | --reverse}] [{{--fg | --bg }] {--black | --red | --green | --yellow | --blue | --magenta | --cyan | --white | --defaultcolor}} | --reset] [{--nulltext | { text [...] }}] ...\n" "${0}" >&2
		printf "NOTE: under normal circumstances, --reset should be the last element.\n" >&2
		printf "If setting both --fg and --bg, use --nulltext between them.\n" >&2
		printf "Environment variable FORCE_COLOR=1 can be used to write color codes to a file.\n" >&2
		exit 1
		;;
	esac
fi

while test $# -gt 0
do
	case "${1}" in
	-bold | --bold)
		boldState=";1"
		;;
	-normal | --normal)
		boldState=";0"
		;;
	-underline | --underling)
		boldState=";4"
		;;
	-blink | --blink)
		boldState=";5"
		;;
	-reverse | --reverse)
		boldState=";7"
		;;
	-fg | --fg)
		fgSel="3"
		;;
	-bg | --bg)
		fgSel="4"
		;;
	-black | --black)
		colorCode="0";
		;;
	-red | --red)
		colorCode="1"
		;;
	-green | --green)
		colorCode="2"
		;;
	-yellow | --yellow)
		colorCode="3"
		;;
	-blue | --blue)
		colorCode="4"
		;;
	-magenta | --magenta)
		colorCode="5"
		;;
	-cyan | --cyan)
		colorCode="6"
		;;
	-white | --white)
		colorCode="7"
		;;
	-defaultcolor | --defaultcolor)
		colorCode="9"
		;;
	-reset | --reset)
		fgSel="0"
		colorCode=""
		boldState=""
		;;
	-nulltext | --nulltext)
		# Set special null text pattern
		text="-nulltext-"
		;;
	*)
		text="${1}"
		;;
	esac
	# if something to say, add it to output line...
	if test -n "${text}" -o $# -eq 1
	then
		case "${terminalType}X" in
		*xtermX | xterm*X) 
			colorSequence="\033[${fgSel}${colorCode}${boldState}m"
			if test "${colorSequence}" != "${lastColorSequence}"
			then
				outputLine="${outputLine}${colorSequence}"
				lastColorSequence="${colorSequence}"
			fi
			;;
		esac
		if test -n "${text}"
		then
			if test "${text}" = '-nulltext-'
			then
				text=""
			fi
			outputLine="${outputLine}${lastText:+ }${text}"
			lastText="${text}"
			text=""
		fi
	fi
	shift
done
printf "${outputLine}\n"
exit 0
