#!/bin/bash
# Filename:      /usr/share/ngcp-ngcpcfg/functions/logs
# Purpose:       helper log functions for ngcpcfg
################################################################################

# console output including timestamps {{{
export timestamp_replacementchars='' # unset by default

console_output() {
  if [ -z "${TIME_FORMAT:-}" ] ; then
    printf -- "%b" "$*"
    return 0
  fi

  local timestamp
  timestamp="$(date "$TIME_FORMAT")"

  # indent depending on number of characters in date output
  export timestamp_replacementchars
  timestamp_replacementchars="$(printf -- "%s: " "$timestamp" | sed 's/./ /g')"
  printf -- "%b" "${timestamp} ${HNAME:-}: $*"
}
# }}}

## logging functions {{{
log_only() {
  # XXX: The NGCPCFG_PID variable should be set by ngcpcfg, but we currently
  # have code that executes helpers directly, where we should have exposed
  # those helpers as new commands. For now we fallback to the current PID.
  logger -t ngcpcfg --id="${NGCPCFG_PID:-$$}" -- "$*"
}

log_info() {
  log_only "$*"
  console_output "$*\n"
}

# info without ending newline
log_info_n() {
  log_only "$*"
  console_output "$*"
}

log_warn() {
  log_only "Warning: $*"
  console_output "Warning: $*\n"
}

# warning without ending newline
log_warn_n() {
  log_only "Warning: $*"
  console_output "Warning: $*"
}

log_error() {
  log_only "Error: $*"
  console_output "Error: $*\n" >&2
}

log_debug() {
  if [ -n "${DEBUG:-}" ] ; then
    log_only "Debug: $*"
    console_output "DEBUG: $*\n" >&2
  fi
}
## }}}
