#!/bin/sh
# shellcheck source=/dev/null
# Logging functions

# LOGFILE variable must be defined upstream by the caller which sources this file
LOGFILE_MAX_SZ_KB=1024

InitLogConfig() {
    VERBOSE=$(_get_ini_var ipfailover2 tracelvl 0)
    if [ "$VERBOSE" != "0" ]; then
        VERBOSE="yes"
        maxsz=$(_get_ini_var ipfailover2 logfile_maxsz_kb 0)
        if [ "$maxsz" != "0" ]; then
            LOGFILE_MAX_SZ_KB="$maxsz"
        fi
        Log "#############################################"
        Log "### Start $$"
        Log "#############################################"
    fi

}

CheckLogRotate() {
    # shellcheck disable=SC1083,SC2012
    sz=$(ls -s "${LOGFILE}" | awk {'print $1'})
    # sz is in kBytes (assuming block size is 1kB. Should be default for most of "ls" versions)
    if [ "$sz" -gt "${LOGFILE_MAX_SZ_KB}" ]; then
        mv "${LOGFILE}" "${LOGFILE}.backup"
    fi
}

Log() {
    if [ "$VERBOSE" = "yes" ]; then
        #echo $d $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 >> ${LOGFILE}
        d=$(date "+%F %T")
        if [ -n "${LOGFILE}" ] ; then
            echo "$d" "$1" >> "${LOGFILE}"
            CheckLogRotate
        else
            echo "$d $1"
        fi
    fi
}

# Used to log the output of a shell command
LogCmd() {
    CMD_OUTPUT=$("$@")

    if [ "$VERBOSE" = "yes" ]; then
        if [ -n "${LOGFILE}" ] ; then
            Log "Output of command: ${*}"
            echo "${CMD_OUTPUT}" >> "${LOGFILE}"
            CheckLogRotate
        else
            echo "${CMD_OUTPUT}"
        fi
    fi

}

# Used to log the content of a file
LogCat() {
    if [ "$VERBOSE" = "yes" ]; then
        if [ -n "${LOGFILE}" ]; then
            cat "$1" >> "${LOGFILE}"
            CheckLogRotate
        else
            cat "$1"
        fi
    fi
}
