#!/usr/bin/env bash
#
#  This file is part of MetaCLADE.
#
#  MetaCLADE is free software: you can redistribute it and/or modify
#  it under the terms of the CeCILL 2.1 Licence
#
#  MetaCLADE is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
#  You should have received a copy of the Licence CeCILL 2.1 along
#  with MetaCLADE. If not, see <https://cecill.info/>.
#


# Common functions and definitions
PV_NAME="MetaCLADE"
PV_VERSION='2.0'
PV_DATE='20200508'

function abspath() { echo "$(cd "$(dirname "$1")"; pwd -P)/$(basename "$1")"; }

function print_error() { echo "[$(date +"%F %T")] error: ${@}" >&2; }
function print_warning() { echo "[$(date +"%F %T")] warning: ${@}" >&2; }
function print_status() { echo "[$(date +"%F %T")] ${@}" >&2; }
function print_version() { echo "${PV_NAME} ${PV_VERSION}-${PV_DATE}"; }

function check_cmds() {
    cmds=("$@")
    declare -a notfound
    for cmd in "${cmds[@]}"; do
        if ! command -v "${cmd}" >/dev/null 2>&1; then
            notfound+=("${cmd}")
        fi
    done
    if [ ${#notfound[@]} -gt 0 ]; then
        print_error "cannot find the following commands: ${notfound[@]}"
        print_error "check your PATH environment variable"
        exit 1
    fi
    return 0
}

function check_pymodules(){
    check_cmds "python3"
    mods=("$@")
    declare -a notfound
    for mod in "${mods[@]}"; do
        if ! python3 -c "import ${mod}" >/dev/null 2>&1; then
            notfound+=("${mod}")
        fi
    done
    if [ ${#notfound[@]} -gt 0 ]; then
        print_error "cannot find the following python3 modules: ${notfound[@]}"
        exit 1
    fi
    return 0
}

function check_files() {
    files=("$@")
    declare -a notfound
    for f in "${files[@]}"; do
        if [ ! -e "${f}" ]; then notfound+=("${f}"); fi
    done
    if [ ${#notfound[@]} -gt 0 ]; then
        print_error "cannot find the following files:"
        for f in "${notfound[@]}"; do echo "$f"; done
        exit 1
    fi
    return 0
}

