#! /bin/bash -e

echo_args="-e"
while getopts :neh OPT; do
    case $OPT in
        n|+n)
            echo_args="-n $echo_args"
            ;;
        e|+e)
            echo_args="-e $echo_args"
            ;;
        h)
            if [ -t 1 -o -S /dev/stdout ]; then
                echo "this is colorful terminal"
            fi
            exit 0
            ;;
        *)
            echo "usage: ${0##*/} [+-ne} [--] ARGS..."
            exit 2
    esac
done

shift $(( OPTIND - 1 ))
OPTIND=1

COLOR=$1
shift

# As requested, let's support Bash 3 (a shell without associative arrays)
if [ x$BASH_VERSINFO != x \
        -a $BASH_VERSINFO -lt 4 ]
then
    hash_support=0
else
    hash_support=1
fi


if [ $hash_support = 1 ]
then
declare -A _COLORS
_COLORS[reset]='\E[00m'
_COLORS[black]='\E[30m'
_COLORS[red]='\E[31m'
_COLORS[yellow]='\E[32m'
_COLORS[green]='\E[33m'
_COLORS[hired]='\033[31;1m'
_COLORS[hiyellow]='\033[1;32m'
_COLORS[higreen]='\033[1;33m'
_COLORS[blue]='\E[34m'
_COLORS[hiblue]='\033[1;34m'
#hiblue=$blue
_COLORS[magenta]='\E[35m'
_COLORS[cyan]='\E[36m'
_COLORS[white]='\E[37m'
_COLORS[bold]='\033[1m'

_COLORS[orange]='\x1b[48;5;209m'
# 209
else
   declare -a _COLORS
   _COLORS=(
"reset:\E[00m"
"black:\E[30;47m"
"red:\E[31;47m"
"green:\E[32;47m"
"yellow:\E[33;47m"
"hired:\033[31;1m"
"hiyellow:\033[1;32m"
"higreen:\033[1;33m"
"blue:\E[34;47m"
"hiblue:\033[1;34m"
#hiblue=$blue
"magenta:\E[35;47m"
"cyan:\E[36;47m"
"white:\E[37;47m"
"bold:\033[1m"
   );
fi

emit_color()
{
if [ $hash_support = 1 ]
then
    echo -n -e "${_COLORS[$COLOR]}"
else
    for info in ${_COLORS[@]} ; do
        KEY=${info%%:*}
        VALUE=${info##*:}
        if [ $KEY = $1 ]
            then
            echo -n -e "$VALUE"
        fi
    done
fi
}



if [ -t 1 -o "${FORCE_COLOR-}" = y -o -S /dev/stdout ]; then
    if [ "${TERM}" = "xterm" \
        -o "${TERM}" = "xterm-256color" \
        -o "${TERM}" = "screen" \
        -o "${TERM}" = "linux" \
        -o "${TERM}" = "rxvt" \
        -o "${TERM}" = "ansi" ]; then
        emit_color $COLOR
        # -n is broken here? cecho hired -ne "ahoj\n"; echo ok
        /bin/echo $echo_args "$@"
        tput sgr0
    else
        echo $echo_args "$@"
    fi
else
    echo $echo_args "$@"
fi

# setab man terminfo
# echoti setaf 5; echo ahoj
