#!/bin/bash

# Copyright: 2023 Virtuozzo International GmbH

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

[ -n "${LOGLIB_VERSION:-}" ] && return 0;
LOGLIB_VERSION="0.1";

VERBOSE=0;
LOG_PATH='/var/log';
LOG_FILE="${LOG_PATH}/${MANAGE_PROGRAM_NAME}.log";

function log() {
    if [[ ${VERBOSE} -gt 0 ]]; then
        echo -n $(date +%D.%k:%M:%S.%N) $action:$subaction [PID: $$] >> ${LOG_FILE};
        echo ": $@" >> ${LOG_FILE};
    fi
    if [[ ${VERBOSE} -gt 1 ]]; then
        echo -n $(date +%D.%k:%M:%S.%N) $action:$subaction [PID: $$];
        echo ": $@"
    fi
}

function forceLog() {
    echo -n $(date +%D.%k:%M:%S.%N) >> ${LOG_FILE};
    echo ": $@" >> ${LOG_FILE};
    if [[ ${VERBOSE} -gt 1 ]]; then
        echo -n $(date +%D.%k:%M:%S.%N);
        echo ": $@"
    fi
}

function warn() {
    local vt=${VERBOSE}
    VERBOSE=1
    log "$@";
    VERBOSE=${vt}
    if [[ ${VERBOSE} -gt 0 ]]; then
        echo "-------------------------------------------" >> ${LOG_FILE};
        echo "$(printStack)" >> ${LOG_FILE};
        echo "-------------------------------------------" >> ${LOG_FILE};
    fi
}

function error() {
    local stack=$(printStack);
    local vt=${VERBOSE}
    VERBOSE=1
    log "$@";
    echo "-------------------------------------------" >> ${LOG_FILE};
    echo "$stack" >> ${LOG_FILE};
    echo "-------------------------------------------" >> ${LOG_FILE};
    VERBOSE=${vt}
    runIfExists "sendErrorMail" "$(echo "$@")" 'Error message'
}


GRAB_OUTPUT="eval [[ \"\$VERBOSE\" -gt \"1\" ]] &&  { tee \$LOG_FILE; exit;} || [[ \"\$VERBOSE\" -gt \"0\" ]] && cat >> \$LOG_FILE || cat >> /dev/null";

