#!/usr/bin/env bash
#
## Common utilities used in various commands

LIBPATH="$(cd "$(dirname "${BASH_SOURCE[0]}")"; pwd -P)"
source ${LIBPATH}/livibetter-backup/log.sh/log.sh

APP_NAME="OPSKIT"
LS_LEVEL=LS_INFO_LEVEL

## Overload log.sh general logging function to correct timestamp on OSX
LSLOG() {
  local LEVEL=$1
  shift
  (( ${LEVEL} < ${LS_LEVEL} )) && return 1
  local TS=$(date +'%Y-%m-%d %H:%M:%S')
  _LS_FIND_LEVEL_STR ${LEVEL}
  local OUTPUT
  eval "OUTPUT=\"[${APP_NAME}]${_LS_LEVEL_FMT}\""
  ## if no message was passed, read it from stdin
  local _MSG
  local args=("$@")
  [[ $# -ne 0 ]] && _MSG=${args[$# - 1]} || _MSG="$(cat)"
  if [[ "${LS_OUTPUT}" = "/dev/stdout" ]] ; then
    echo -ne "${_LS_LEVEL_BEGIN}${OUTPUT} "
    echo -n  "${_MSG}"
    echo -e "${_LS_LEVEL_END}"
  else
    echo -ne "${_LS_LEVEL_BEGIN}${OUTPUT} " >> "${LS_OUTPUT}"
    echo -n  "${_MSG}"                      >> "${LS_OUTPUT}"
    echo -e  "${_LS_LEVEL_END}"             >> "${LS_OUTPUT}"
  fi
}

alias log_d="LSDEBUG $1"
alias log_i="LSINFO $1"
alias log_w="LSWARNING $1"
alias log_e="LSERROR $1"
alias log_c="LSCRTICAL $1"

command_exists() {
  command -v $1 >/dev/null 2>&1 || return 1
}
