#!/bin/bash

# shellcheck disable=SC1091

set -o errexit
set -o nounset
set -o pipefail

[ -n "${DEBUG:+1}" ] && set -x

# Load libraries
. /opt/easysoft/scripts/liblog.sh
. /opt/easysoft/scripts/libmysql.sh
. /opt/easysoft/scripts/libfs.sh

# Load Apache/PHP//ZenDAS environment variables
. /etc/s6/s6-init/envs

#==================================#
# Prepare persistence directories. #
#==================================#
info "Prepare persistence directories."
for dir in $PERSISTENCE_LIST
do
    # Ensure a directory exists and,is owned by the given user
    ensure_dir_exists "$dir" "www-data"

    if [ "$dir" == "/data/zendas/www/data" ];then
       # Interim processing
       chmod 777 "$dir"
       ln -s "$dir" /apps/zendas/www/
    fi
done

#=====================#
#   Prepare PHP       #
#=====================#
PHP_CLI_INI="/etc/php/7.4/cli/php.ini"
PHP_APACHE_INI="/etc/php/7.4/apache2/php.ini"

info "Render php.ini with environment variables."
/usr/bin/render-template /etc/php/7.4/php.ini.tpl > ${PHP_CLI_INI}
/usr/bin/render-template /etc/php/7.4/php.ini.tpl > ${PHP_APACHE_INI}

#=====================#
#   Prepare Apache    #
#=====================#
ZENTAO_SITE_CFG="/etc/apache2/sites-available/00-zendas.conf"

info "Render apache sites config with envionment variables."
/usr/bin/render-template ${ZENTAO_SITE_CFG}.tpl > $ZENTAO_SITE_CFG

# Check and waiting mysql to be ready
wait_for_mysql || exit 1

# Initialize zendas database
mysql_init_db "$MYSQL_DB"