#!/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 "${MATHLIB_VERSION:-}" ] && return 1;
MATHLIB_VERSION="0.1";

command -v bc >/dev/null 2>&1 || return 0;

FLOAT_SCALE=4;

function floatEval() {
    local stat=0 result=0.0;
    [[ ${#} -gt 0 ]] && {
        result=$(LC_ALL=C printf "%.${FLOAT_SCALE}f" $(echo "scale=${FLOAT_SCALE}; ${*}" | bc -q 2>/dev/null));
        stat=${?};
        [[ ${stat} -eq 0  &&  -z "${result}" ]] && stat=1;
    }
    echo ${result};
    return ${stat};
}

function floatCond() {
    local cond=0;
    [[ ${#} -gt 0 ]] && {
        cond=$(LC_ALL=C echo "${*}" | bc -q 2>/dev/null)
        [[ -z "${cond}" ]] && cond=0;
        [[ "${cond}" != 0  &&  "${cond}" != 1 ]] && cond=0;
    }
    local stat=$((cond == 0));
    return ${stat};
}
