#!/bin/bash
chmod a+x /bin/wait-for-it
#echo "---------------> Wait redis"
#wait-for-it -t 0 redis:6379

echo "---------------> Wait mysql"
wait-for-it -t 0 mysql:3306

set -e

cd /var/www/html/advanced/

# template prepare

cp -r /templates/ /templates.copy/

r="$RANDOM"
for f in $(find /templates.copy/ -regex '.*\.tpl\.?php' 2> /dev/null); do
    sed -e "s/<?/<<<$r\&\&\&/g" -e "s/?>/\&\&\&$r>>>/g" -e 's/<%/<?/g' -e 's/%>/?>/g' < $f | php | sed -e "s/<<<$r\&\&\&/<?/g" -e "s/\&\&\&$r>>>/?>/g" > "${f%\.tplphp}"
    rm -f $f
done

cp -r /templates.copy/sites-enabled/ /etc/apache2/
cp /templates.copy/apache2.conf /etc/apache2/
cp /templates.copy/php.ini /usr/local/etc/php/conf.d/base.ini

if [ "$XDEBUG_ENABLE" = 1 ]; then
    echo "---------------> start xdebug"
    mkdir -p /var/log/xdebug/
    mkdir -p /var/log/xdebug/profiler
    touch /var/log/xdebug/remote_log.log
    cp /templates.copy/xdebug.ini /usr/local/etc/php/conf.d/xdebug.ini
    docker-php-ext-enable xdebug
    chown -R www-data:www-data /var/log/xdebug
fi

if ! [ -d "./vendor/yiisoft/" ]; then
    COMPOSER_MEMORY_LIMIT=-1 composer install --optimize-autoloader
    chmod -R a+w ./vendor
    php init --env=Development --overwrite=All --delete=All
    cp /templates.copy/main-local.php /var/www/html/advanced/common/config
    chmod -R +w ./*/config/
    chmod -R a+w ./*/web/assets
    chmod -R a+w ./*/runtime
    php yii migrate --interactive=0
fi

echo "---------------> Starting queue worker"
nohup php yii queue/listen > /dev/null 2>&1 &

#cache folder permission
[ -d "./temp" ] && chown -R www-data:www-data ./temp

#screen -d -m -S queue ./queue.bash

exec "$@"
