#!/bin/sh
set -ev

# Volumes
MARIADB_CONF="${VOLUMES_DIR}/crismapp/mariadb_conf"
MARIADB_DATA="${VOLUMES_DIR}/crismapp/mariadb_data"
CRISMAPP_CONF="${VOLUMES_DIR}/crismapp/crismapp_conf"
CRISMAPP_LAYER="${LAYERS_DIR}/crismapp_0.0.1-200411"

# Create MariaDB instance
install -o 100000 -g 100000 -m 755 -d ${MARIADB_CONF}
install -o 103306 -g 103306 -m 750 -d ${MARIADB_DATA}
install -o 100000 -g 100000 -m 644 mariadb_conf/my.cnf ${MARIADB_CONF}/my.cnf
spoc-container exec crismapp-mariadb -- mysql_install_db --user=mysql --datadir=/var/lib/mysql --auth-root-authentication-method=socket --skip-test-db

# Create database
export CRISMAPP_PWD=$(head -c 18 /dev/urandom | base64 | tr -d '+/=')
spoc-container start crismapp-mariadb
envsubst <createdb.sql | spoc-container exec crismapp-mariadb -- mysql

# Populate database
cat ${CRISMAPP_LAYER}/srv/crismapp/6/disertace.sql | spoc-container exec crismapp-mariadb -- mysql crismapp

# Configure Crismapp
install -o 108080 -g 108080 -m 750 -d ${CRISMAPP_CONF}
envsubst <crismapp_conf/config.php | sed -e 's/§/$/g' | install -o 108080 -g 108080 -m 600 /dev/stdin ${CRISMAPP_CONF}/config.php

# Stop services required for setup
spoc-container stop crismapp-mariadb

# Register application
vmmgr register-app crismapp crismapp
