#!/bin/bash
MAGENTO_USERNAME_PROP="http-basic.repo.magento.com.username"
MAGENTO_PASSWORD_PROP="http-basic.repo.magento.com.password"
hash composer 2>/dev/null && IS_COMPOSER_ON_HOST=true

if [ $IS_COMPOSER_ON_HOST ]; then
    PUBLIC_KEY="$(composer config --global $MAGENTO_USERNAME_PROP 2>/dev/null)"
    PRIVATE_KEY="$(composer config --global $MAGENTO_PASSWORD_PROP 2>/dev/null)"
fi

if [ -z "$PUBLIC_KEY" ] || [ -z "$PRIVATE_KEY" ]; then
    exec < /dev/tty
    echo
    echo "Composer authentication required (repo.magento.com public and private keys):"
    read -r -p "    Username: " PUBLIC_KEY
    read -r -p "    Password: " PRIVATE_KEY
    echo
    exec <&-
fi

if [ -z "$PUBLIC_KEY" ] || [ -z "$PRIVATE_KEY" ]; then
    echo "Please setup Composer auth for repo.magento.com to continue." && exit 1
fi

# Output must be piped otherwise file descriptor errors occur. Carriage returns?
echo "composer config --global http-basic.repo.magento.com ${PUBLIC_KEY} ${PRIVATE_KEY}" | bin/clinotty bash -

# Also make sure alternate auth.json is setup (Magento uses this internally)
bin/clinotty [ -d "./var/composer_home" ] && cp /var/www/.composer/auth.json ./var/composer_home/auth.json

echo "Composer auth has been setup."