# Set up terminal capabilities (for displaying in bold and colors).
#
# See terminfo(5) for a list of terminal capability strings.
#
# tput returns an empty string (and exits with a nonzero status) for
# unsupported string capabilities, and -1 for unsupported integer
# capablilities.
BOLD=$(tput bold) || BOLD=
NORMAL=$(tput sgr0) || NORMAL=
NCOLORS=$(tput colors)
# If the terminal doesn't support color at all, these will remain null.
RED=
GREEN=
YELLOW=

# We want different foreground color numbers if we have a terminal capable of
# more than 8, because generally the contrast is bad if we use the low-numbered
# colors (bold helps, but only so much).  On terminals truly capable of only 8
# colors, we have to rely on the implementation to provide good contrast.
if [ -n "$NCOLORS" ]
then
    if [ $NCOLORS -gt 8 ]
    then
        RED=$(tput setaf 9)
        GREEN=$(tput setaf 10)
        YELLOW=$(tput setaf 11)
        CYAN=$(tput setaf 14)
    # This is an exact equality match on purpose.  tput will report -1 for a
    # truly monochrome terminal and in that case we don't want to mess with
    # the setaf capability at all.
    elif [ $NCOLORS -eq 8 ]
    then
        RED=$(tput setaf 1)
        GREEN=$(tput setaf 2)
        YELLOW=$(tput setaf 3)
        CYAN=$(tput setaf 6)
    fi
fi

# Emit diagnostic message.
# @params: a set of strings comprising a human-intelligible message
#
# Display the diagnostic message itself in bold.
_print () {
    echo "${PROGNAME:-(unknown program)}: $BOLD$*$NORMAL"
}

# Emit debugging message to standard error.
# @params: a set of strings comprising a human-intelligible message
debug () {
    _print "${CYAN}debug: $*" >&2
}

# Emit informational message to standard error.
notice () {
    _print "${GREEN}notice: $*" >&2
}

# Emit warning message to standard error.
warn () {
    _print "${YELLOW}warning: $*" >&2
}

# Emit error message to standard error.
fail () {
    _print "${RED}error: $*" >&2
}
