#!/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/>.
#

# Install and initialize Composer in the given directory
#
# The installed version is defined by `$composer_version` which should be defined
# as global prior to calling this helper.
#
# Will use `$install_dir` as workdir unless `$composer_workdir` exists (but that shouldnt be necessary)
#
# usage: ynh_composer_install
ynh_composer_install() {
    local workdir="${composer_workdir:-$install_dir}"

    [[ -n "${composer_version}" ]] || ynh_die "\$composer_version should be defined before calling ynh_composer_install. (In the past, this was called \$YNH_COMPOSER_VERSION)"

    [[ ! -e "$workdir/composer.phar" ]] || ynh_safe_rm "$workdir/composer.phar"

    local composer_url="https://getcomposer.org/download/$composer_version/composer.phar"

    # NB. we have to declare the var as local first,
    # otherwise 'local foo=$(false) || echo 'pwet'" does'nt work
    # because local always return 0 ...
    local out
    # Timeout option is here to enforce the timeout on dns query and tcp connect (c.f. man wget)
    out=$(wget --tries 3 --no-dns-cache --timeout 900 --no-verbose --output-document="$workdir/composer.phar" "$composer_url" 2>&1) \
        || ynh_die "$out"
}

# Execute a command with Composer
#
# Will use `$install_dir` as workdir unless `$composer_workdir` exists (but that shouldnt be necessary)
#
# You may also define `composer_user=root` prior to call this helper if you
# absolutely need composer to run as root, but this is discouraged...
#
# usage: ynh_composer_exec commands
ynh_composer_exec() {
    local workdir="${composer_workdir:-$install_dir}"

    COMPOSER_HOME="$workdir/.composer" \
        COMPOSER_MEMORY_LIMIT=-1 \
        sudo -E -u "${composer_user:-$app}" \
        "php$php_version" "$workdir/composer.phar" "$@" \
        -d "$workdir" --no-interaction --no-ansi 2>&1
}
