#!/usr/bin/env bash
#
# Copyright (c) 2024 YunoHost Contributors
#
# This file is part of YunoHost (see https://yunohost.org)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

# Entrypoint for the helpers scripts
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)

# Helpers version can be specified via an environment variable or default to 1.
YNH_HELPERS_VERSION=${YNH_HELPERS_VERSION:-1}

# This is a trick to later only restore set -x if it was set when calling this script
readonly XTRACE_ENABLE=$(set +o | grep xtrace)
set +x

YNH_HELPERS_DIR="$SCRIPT_DIR/helpers.v${YNH_HELPERS_VERSION}.d"
case "$YNH_HELPERS_VERSION" in
    "1" | "2" | "2.1")
        readarray -t HELPERS < <(find -L "$YNH_HELPERS_DIR" -mindepth 1 -maxdepth 1 -type f | sort)
        source $YNH_HELPERS_DIR/getopts
        for helper in "${HELPERS[@]}"; do
            [ -r "$helper" ] && source "$helper"
        done
        ;;
    *)
        echo "Helpers are not available in version '$YNH_HELPERS_VERSION'." >&2
        exit 1
        ;;
esac

eval "$XTRACE_ENABLE"
