#!/bin/bash -ex

source _helper_functions.sh


########################################
##               Config               ##
########################################

#CONTAINER_TIMEOUT=60   # stop container after this timeout (does not work with gitlab ci)


### Config Database Container ###

DB_CONTAINER_NAME=    # if empty choose random
DB_PORT=0    # if set to 0 choose random
MYSQL_ROOT_PASSWORD=MN7HKEB7AnvdVKQE
MYSQL_USER=typo3
MYSQL_PASSWORD=jP36XnRdGvfmS7RL
QFQ_DATABASE=qfq_db
T3_DATABASE=t3_db


### Config Typo3 Container ###

T3_IMAGE=typo3-qfq
T3_CONTAINER_NAME=    # if empty choose random
T3_PORT=0    # if set to 0 choose random
# T3_ADMINO_PASSWORD=    # typo3 password for user admino (if not set, then default is used)
# T3_INSTALL_PASSWORD_HASH=<ReplaceWithHashGeneratedByTypo3InstallTool>
# T3_REPLACE_ENCRYPTION_KEY=yes  # generate new key using /dev/urandom


########################################
##            Pre Process             ##
########################################

source run_qfq_docker.output && echo "File run_qfq_docker.output already exists. Delete it first. Abort." \
    && exit 1 || true


########################################
##           DB Container             ##
########################################

DB_CONTAINER=$(docker run -d --name "${DB_CONTAINER_NAME}" \
    -p ${DB_PORT}:3306 \
    -e MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD} \
    -e MYSQL_USER=${MYSQL_USER} \
    -e MYSQL_PASSWORD=${MYSQL_PASSWORD} \
    mariadb:latest \
    --character-set-server=utf8 \
    --collation-server=utf8_general_ci)
DB_PORT="$(getHostPort 3306 ${DB_CONTAINER})"
addUsernameToContainerName ${DB_CONTAINER}

echo "
DB_CONTAINER=${DB_CONTAINER}
DB_PORT=${DB_PORT}
" >> run_qfq_docker.output

if [[ "${CONTAINER_TIMEOUT}" ]]; then
    removeContainerAfterTimeout ${CONTAINER_TIMEOUT} ${DB_CONTAINER}
fi

### import database files ###

# HACK: Have to retry until database is ready. Database loading could be done earlier in image build process.
# As described here: https://stackoverflow.com/a/49680802
# Instead of copying the sql files in the dockerfile we could mount them in a volume!
tries=0
until mysql -u root --password=${MYSQL_ROOT_PASSWORD} --port=${DB_PORT} -h 127.0.0.1 \
    -e "CREATE DATABASE ${T3_DATABASE}; CREATE DATABASE ${QFQ_DATABASE}"
do
	tries=$((tries+1))
    if [[ "${tries}" -gt 60 ]]; then
        echo "Timeout: could not connect to database."
        exit 1;
    fi
    echo "Try again"
    sleep 1
done

mysql -u root --password=${MYSQL_ROOT_PASSWORD} --port=${DB_PORT} -h 127.0.0.1 -D ${T3_DATABASE} < db_fixture_t3.sql
mysql -u root --password=${MYSQL_ROOT_PASSWORD} --port=${DB_PORT} -h 127.0.0.1 -D ${QFQ_DATABASE} < db_fixture_qfq.sql
mysql -u root --password=${MYSQL_ROOT_PASSWORD} --port=${DB_PORT} -h 127.0.0.1 \
    -e "GRANT ALL PRIVILEGES ON *.* TO '${MYSQL_USER}'@'%';"


########################################
##           T3 Container             ##
########################################

T3_CONTAINER=$(docker run -d --name "${T3_CONTAINER_NAME}" -p ${T3_PORT}:80 --link ${DB_CONTAINER}:db ${T3_IMAGE})
T3_PORT="$(getHostPort 80 ${T3_CONTAINER})"
addUsernameToContainerName ${T3_CONTAINER}

echo "
T3_CONTAINER=${T3_CONTAINER}
T3_PORT=${T3_PORT}
" >> run_qfq_docker.output

if [[ "${CONTAINER_TIMEOUT}" ]]; then
    removeContainerAfterTimeout ${CONTAINER_TIMEOUT} ${T3_CONTAINER}
fi

### Write config files ###

# QFQ config
echo "
<?php
return [
    'DB_1_USER' => '${MYSQL_USER}',
    'DB_1_SERVER' => 'db',
    'DB_1_PASSWORD' => '${MYSQL_PASSWORD}',
    'DB_1_NAME' => '${QFQ_DATABASE}',
];" > config.qfq.php
docker cp config.qfq.php ${T3_CONTAINER}:/var/www/html/typo3conf/config.qfq.php
rm config.qfq.php
docker exec ${T3_CONTAINER} chown www-data:www-data /var/www/html/typo3conf/config.qfq.php

# Typo3 config
docker exec ${T3_CONTAINER} sed -i -e "s/<MYSQL_USER>/${MYSQL_USER}/g" /var/www/html/typo3conf/LocalConfiguration.php
docker exec ${T3_CONTAINER} sed -i -e "s/<MYSQL_PASSWORD>/${MYSQL_PASSWORD}/g" /var/www/html/typo3conf/LocalConfiguration.php
docker exec ${T3_CONTAINER} sed -i -e "s/<T3_DATABASE>/${T3_DATABASE}/g" /var/www/html/typo3conf/LocalConfiguration.php
if [[ "${T3_INSTALL_PASSWORD_HASH}" ]]; then
	current_hash='s/$pbkdf2-sha256$25000$1h4tjST5Wv.PyZcwfIIVvQ$kUl8homXlnaDohmt6ki0Vsji9tEaJ6tQ9vnymDCfYAY'
	docker exec ${T3_CONTAINER} sed -i -e "s/${current_hash}/${T3_INSTALL_PASSWORD_HASH}/g" \
	    /var/www/html/typo3conf/LocalConfiguration.php
fi
if [[ "${T3_REPLACE_ENCRYPTION_KEY}" ]]; then
    key=$(hexdump -n 48 -e '4/4 "%08X" 1 "\n"' /dev/urandom)
    key=$(echo "${key}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')
    old_key=50c80989f47d1097a66ed9d584b935dca4ecf881ffaf814701572906cb6f0cd894d10da8859d1d9b2241e0fe0fb2692d
    docker exec ${T3_CONTAINER} sed -i -e "s/${old_key}/${key}/g" /var/www/html/typo3conf/LocalConfiguration.php
fi

### Deploy qfq extension to container ###

# This is slow. Could also be done in docker image build process.
# Or could mount qfq as a volume to the typo3-qfq container. (might cause problems)
if ! [[ $1 == "-no-deploy" ]]; then
    ./deploy_to_container.sh
fi


########################################
##           Post Process             ##
########################################

### Set Typo3 Admin Pass ###

if [[ "${T3_ADMINO_PASSWORD}" ]]; then
    T3_ADMINO_PASSWORD_HASH=$(curl http://127.0.0.1:${T3_PORT}/typo3conf/ext/qfq/Classes/External/hashPassword.php?pw=${T3_ADMINO_PASSWORD})
	mysql -u root --password=${MYSQL_ROOT_PASSWORD} --port=${DB_PORT} -h 127.0.0.1 -D ${T3_DATABASE} \
	    -e "UPDATE be_users SET password='${T3_ADMINO_PASSWORD_HASH}' WHERE username='admino';"
fi


########################################
##           User Output              ##
########################################

echo "Finished. Go to:"
echo "localhost:${T3_PORT}"