#!/bin/bash

# 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
}