#!/bin/sh
set -ev

# Volumes
MARIADB_CONF="${VOLUMES_DIR}/mifosx/mariadb_conf"
MARIADB_DATA="${VOLUMES_DIR}/mifosx/mariadb_data"
MIFOSX_CONF="${VOLUMES_DIR}/mifosx/mifosx_conf"

# 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 mifosx-mariadb -- mysql_install_db --user=mysql --datadir=/var/lib/mysql --auth-root-authentication-method=socket --skip-test-db

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

# Configure Mifos X
install -o 100000 -g 100000 -m 755 -d ${MIFOSX_CONF}
envsubst <mifosx_conf/context.xml | install -o 100000 -g 100000 -m 644 /dev/stdin ${MIFOSX_CONF}/context.xml
install -o 100000 -g 100000 -m 644 mifosx_conf/server.xml ${MIFOSX_CONF}/server.xml

# Populate database
spoc-container exec mifosx -- cat /tmp/mifospltaform-tenants-first-time-install.sql | spoc-container exec mifosx-mariadb -- mysql mifosplatform-tenants
envsubst <schemapwd.sql | spoc-container exec mifosx-mariadb -- mysql mifosplatform-tenants

# Populate database
spoc-container start mifosx
until grep -q 'org.apache.catalina.startup.Catalina.start Server startup' /var/log/spoc/mifosx.log; do
    sleep 1
done
spoc-container stop mifosx

# Fix missing previous_run_status column
echo 'ALTER TABLE `scheduled_email_campaign` ADD `previous_run_status` VARCHAR(10) NULL;' | spoc-container exec mifosx-mariadb -- mysql mifostenant-default

# Update admin account
export MIFOSX_ADMIN_USER="admin"
export MIFOSX_ADMIN_EMAIL="admin@example.com"
export MIFOSX_ADMIN_PWD=$(head -c 12 /dev/urandom | base64 | tr -d '+/=')
export MIFOSX_ADMIN_HASH=$(echo -n "${MIFOSX_ADMIN_PWD}{1}" | sha256sum | awk '{print $1}')
envsubst <adminpwd.sql | spoc-container exec mifosx-mariadb -- mysql mifostenant-default

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

# Register application
vmmgr register-app mifosx mifosx "${MIFOSX_ADMIN_USER}" "${MIFOSX_ADMIN_PWD}"
