#!/bin/bash
SOURCE="$0"
source /usr/lib/elive-tools/functions
# EL_REPORTS="1"
# el_make_environment
# . gettext.sh
# TEXTDOMAIN="elive-tools"
# export TEXTDOMAIN
#
#
#===  FUNCTION  ================================================================
#          NAME:  el_prettify_to_html
#   DESCRIPTION:  prettify a message or diff to html format
#    PARAMETERS:  $1 = message
#       RETURNS:  html string
#===============================================================================
el_prettify_to_html(){
    local message="$*"
    local output

    # update: disabled for now to see if works good
    # if [[ "$message" =~ "<span" ]] || [[ "$message" =~ "<h3>" ]] ; then
    #     # do not process something that has already html tags
    #     # output="$message"
    #     true
    # else
        output="$( printf "%s" "$message" | sed 's|\\n|<br>|g' |
            awk '{ if ($1 ~ /^\s*\-/) print "<span style=\"color:#a74000;font-family:monospace;\">"$0"</span>" ;
                    else if ($0 ~ /@@.*@@/ || $0 ~ /^diff --git /) print "<span style=\"color:#e0a300;font-family:monospace;\">"$0"</span>" ;
                    else if ($1 ~ /^\s*\+/) print "<span style=\"color:#00a742;font-family:monospace;\">"$0"</span>" ;
                    else if ($1 ~ /^\s*\+\+\+/) print "<span style=\"color:blue;font-family:monospace;\">"$0"</span>" ;
                    else if ($1 ~ /^\s*\-\-\-/) print "<span style=\"color:#614700;font-family:monospace;\">"$0"</span>" ;
                    else if ($1 ~ /^E:/) print "<span style=\"color:red;\">"$0"</span>" ;
                    else if ($1 ~ /^W:/) print "<span style=\"color:#e0a300;\">"$0"</span>" ;
                    else if ($0 ~ /^\s*(#|\/\/)\s/ || $0 ~ /^index [0-9a-f]+\.\.[0-9a-f]+/) print "<span style=\"color:#888888;\">"$0"</span>" ;
                    else {
                        if ($0 ~ /[Ww]arning|[Ee]rror/) print "<b>"$0"</b>" ;
                        else print $0
                    } }' )"
    # fi

    echo -e "$output" | sed -e 's|\\n|<br>|g' | tr '\n' '@' | sed -e 's|@$||g' -e 's|@|<br>|g'
    echo ""
}

# Main logic to handle arguments or pipe
if [[ -t 0 ]]; then
    # Input from arguments
    input="$*"
else
    # Input from pipe
    input="$(cat)"
fi

if [[ -n "$input" ]]; then
    el_prettify_to_html "$input"
fi
