#!/usr/bin/env bash

set -ex

. ${0%/*}/_functions.sh

ok "* web administration..."

(find /opt/admin -type d -name ".git" && find /opt/admin -name ".gitignore" && find /opt/admin -name ".gitkeep") | xargs rm -rf

rm -Rf /opt/admin/var/cache
rm -Rf /opt/admin/var/logs

mkdir /opt/www/.well-known 2> /dev/null || true
chown mail:mail -R /opt/www/.well-known

cd /opt/admin

export COMPOSER_ALLOW_SUPERUSER=1

EXPECTED_SIGNATURE="$(wget -q -O - https://composer.github.io/installer.sig)"
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
ACTUAL_SIGNATURE="$(php -r "echo hash_file('SHA384', 'composer-setup.php');")"

if [ "$EXPECTED_SIGNATURE" != "$ACTUAL_SIGNATURE" ]
then
    >&2 echo 'ERROR: Invalid installer signature'
    rm composer-setup.php
    exit 1
fi

php composer-setup.php --disable-tls
php -r "unlink('composer-setup.php');"

if [ "$APP_ENV" = "dev" ]; then
    mkdir -p /opt/admin/tests/Test/horde 2> /dev/null || true # dir must be present for composer build without tests
    export SYMFONY_ENV=dev
    COMPOSER_HOME=/cache/composer php composer.phar install || true
else
    export SYMFONY_ENV=prod
    COMPOSER_HOME=/cache/composer php composer.phar install --no-dev --optimize-autoloader --classmap-authoritative || true
fi

mkdir /opt/admin/var/cache 2> /dev/null || true
mkdir /opt/admin/var/cache/dev 2> /dev/null || true
mkdir /opt/admin/var/cache/prod 2> /dev/null || true
mkdir /opt/admin/var/cache/test 2> /dev/null || true

mkdir /opt/admin/var/logs 2> /dev/null || true


chown mail:mail /opt/admin/var/cache -R
chown mail:mail /opt/admin/var/logs -R

##########################################################################

