#!/bin/bash

[ -n "$_INCGD_logging" ] && return || readonly _INCGD_logging=1


log_dir="/var/log/app-setup-scalet"
log_filename="`basename $log_dir`.log"
log_quiet="${log_quiet:-no}"
log_level="${log_level:-8}"

_OUT_FD=2

_LOG_LEVEL_DEBUG=8
_LOG_LEVEL_INFO=4
_LOG_LEVEL_ERROR=2
_LOG_LEVEL_FATAL=1

_log_write()
{
    LEVEL=$1; shift
    MSG="$*"

    # Check that current log level is greater or equal to message level
    if [[ "$LEVEL" -gt "$log_level" ]]; then
        return
    fi

    # Touch log file
    [[ -e "${log_dir}/${log_filename}" ]] || touch "${log_dir}/${log_filename}"

    if [[ -e "$log_dir" ]] && [[ -w "${log_dir}/${log_filename}" ]]; then
        date=`date +'%F %T'`
        echo -e "$date $MSG" | sed -r "s/\x1b\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" >> "${log_dir}/${log_filename}"
    fi

    # Check if we should echo to console
    if [[ ! "$log_quiet" =~ ^[y|t|1] ]] && [[ -t ${_OUT_FD} ]]; then
        echo -e "$MSG" >&${_OUT_FD}
    fi
}

debug()
{
    MSG="\e[37m\e[1mDEBUG:\e[21m \e[90m$*\e[0m"
    _log_write ${_LOG_LEVEL_DEBUG} "$MSG"
}

info()
{
    MSG="\e[1mINFO:\e[21m $*\e[0m"
    _log_write ${_LOG_LEVEL_INFO} "$MSG"
}

error()
{
    MSG="\e[33m\e[1mERROR:\e[21m $*\e[0m"
    _log_write ${_LOG_LEVEL_ERROR} "$MSG"
}

fatal()
{
    MSG="\e[31m[\e[1mFATAL:\e[21m $*\e[0m"
    _log_write ${_LOG_LEVEL_FATAL} "$MSG"
}

# Don't do anything if we're in main process
if [[ "scarlet-init" == $(basename $0) ]]; then
    return 2> /dev/null || exit 0
fi

### BRAIN DAMAGE ALERT ###
# Bash FD manipulations below
# Intercept output of all called programs, and put it into logger line by line

_stdout()
{
    while IFS='' read -r line; do
        MSG="AUX STDOUT: $line"
        _log_write $_LOG_LEVEL_DEBUG "$MSG"
    done
}

_stderr()
{
    while IFS='' read -r line; do
        MSG="AUX STDERR: $line"
        _log_write $_LOG_LEVEL_DEBUG "$MSG"
    done
}

_OUT_FD=3
exec 3>&2
exec 1> >(_stdout)
exec 2> >(_stderr)
