#!/usr/bin/env bash

#* --------------------------------------------------------------------- */
#*                         log configure                                 */
#* --------------------------------------------------------------------- */
### Define logging color
COLOR_ORIGIN="\033[0m"
COLOR_GREEN="\033[32m"
COLOR_YELLOW="\033[33m"
COLOR_RED="\033[31m"

### Define logging level
LOGGER_LEVEL="3"

### Define common logger
function logger() {
    cur_level=$1
    cur_type=$2
    cur_color=$3
    shift && shift && shift
    cur_msg=$*

    [[ ${LOGGER_LEVEL} -lt ${cur_level} ]] && return 0

    pre_fix="${cur_color}[${cur_type}][$(date +%F)][$(date +%T)]"
    pos_fix="${COLOR_ORIGIN}"
    if [[ ${cur_level} -eq 1 ]]
    then
        echo -e "${pre_fix} ${cur_msg} ${pos_fix}" >&2
    else
        echo -e "${pre_fix} ${cur_msg} ${pos_fix}"
    fi
}

function common::debug() {
    logger 4 "DEBUG" ${COLOR_GREEN} $*
}

### Define info logger
function common::info() {
    logger 3 "NOTICE" ${COLOR_GREEN} $*
}

### Define warning logger
function common::warning() {
    logger 2 "WARNING" ${COLOR_YELLOW} $*
}

### Define fatal logger
function common::fatal() {
    logger 1 "FATAL" ${COLOR_RED} $*
    exit 1
}

function common::in_array() {
    local match=$1
    shift
    local elements=("${@}")
    for element in "${elements[@]}"; do
        [[ "${element}" == "${match:-}" ]] && return 0;
    done
    return 1
}

# common::version_ge "$v1" "$v2" checks whether "v1" is greater or equal to "v2"
# https://stackoverflow.com/questions/16989598/bash-comparing-version-numbers
function common::version_ge() {
    [ "$(printf '%s\n' "$1" "$2" | sort -V | head -n1)" = "$2" ]
}
