#!/usr/bin/env bash

DATE_FMT="+%s"

msg() {
  local message="$*"
  [ -z "$message" ] && return
  if [ -t 1 ]
  then
    printf "%b\n" "$message"
  else
    log "$message"
  fi
}

log() {
   local message="${*-}"
   [ -z "$message" ] && return
   printf "%s %b\n" "$(date $DATE_FMT)" "$message"
}

debug() {
  local message="$*"
  [[ -z $DEBUG || $DEBUG -ne 1 ]] && return 
  [ -z "$message" ] && return
  message="DEBUG [${BASH_SOURCE[1]}:${FUNCNAME[1]}]: $message"
  if [ -t 2 ]
  then
    >&2 msg "\e[34m$message\e[0m"
  else
    >&2 log "$message"
  fi
}

error() {
  local message="$*"
  [ -z "$message" ] && return 
  message="ERROR: $message"
  if [[ -n $DEBUG && $DEBUG -eq 1 ]]
  then
    message="$message\n\tstack trace:\n"
    for (( i=1; i<${#FUNCNAME[@]}; i++ ))
    do
      message="${message}\t  source:${BASH_SOURCE[i]}"
      message="${message} function:${FUNCNAME[$i]}"
      message="${message} line:${BASH_LINENO[$i-1]}\n" 
    done
  fi
  if [ -t 2 ]
  then
    >&2 msg "\e[31m$message\e[0m"
  else
    >&2 log "$message"
  fi
}
