#!/usr/bin/with-contenv bash

echo "**** Setting up PHP configuration files ****"
if [ ! -d /config/.php ]; then
    cp -rf /etc/php /config/.php
    lsiown -R abc:abc /config/.php
fi
rm -rf /etc/php
ln -s /config/.php /etc/php

if ! [ "${ENABLE_COMPOSER}" = "yes" ]; then
    echo "**** Composer will not be installed ****"
    exit 0
fi

echo "**** Installing Composer ****"

if ! command -v php &> /dev/null; then
    echo "** Missing installed PHP! **"
    exit 127;
fi

EXPECTED_CHECKSUM="$(php -r 'copy("https://composer.github.io/installer.sig", "php://stdout");')"
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
ACTUAL_CHECKSUM="$(php -r "echo hash_file('sha384', 'composer-setup.php');")"

if [ "$EXPECTED_CHECKSUM" != "$ACTUAL_CHECKSUM" ]
then
    echo "** ERROR: Invalid installer checksum **"
    rm composer-setup.php
    exit 1
fi

php composer-setup.php --quiet
RESULT=$?
rm composer-setup.php
if [ "${RESULT}" = "0" ]; then
    echo "** Installing composer system wide **"
    mv composer.phar /usr/local/bin/composer
fi
exit $RESULT
