#!/bin/sh
set -ev

# Volumes
POSTGRES_DATA="${VOLUMES_DIR}/dhis2/postgres_data"
DHIS2_CONF="${VOLUMES_DIR}/dhis2/dhis2_conf"
DHIS2_DATA="${VOLUMES_DIR}/dhis2/dhis2_data"

# Create Postgres instance
install -o 105432 -g 105432 -m 700 -d ${POSTGRES_DATA}
spoc-container exec dhis2-postgres -- initdb -D /var/lib/postgresql

# Configure Postgres
install -o 105432 -g 105432 -m 600 postgres_data/postgresql.conf ${POSTGRES_DATA}/postgresql.conf
install -o 105432 -g 105432 -m 600 postgres_data/pg_hba.conf ${POSTGRES_DATA}/pg_hba.conf

# Create databases
export DHIS2_PWD=$(head -c 18 /dev/urandom | base64 | tr -d '+/=')
spoc-container start dhis2-postgres
envsubst <createdb.sql | spoc-container exec dhis2-postgres -- psql

# Configure DHIS2
install -o 108080 -g 108080 -m 750 -d ${DHIS2_CONF}
install -o 108080 -g 108080 -m 750 -d ${DHIS2_DATA}
envsubst <dhis2_conf/dhis.conf | install -o 108080 -g 108080 -m 640 /dev/stdin ${DHIS2_CONF}/dhis.conf
install -o 108080 -g 108080 -m 640 dhis2_conf/server.xml ${DHIS2_CONF}/server.xml

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

# Update admin account
export DHIS2_ADMIN_USER="admin"
export DHIS2_ADMIN_PWD=$(head -c 12 /dev/urandom | base64 | tr -d '+/=')
export DHIS2_ADMIN_HASH=$(python3 -c "import bcrypt; print(bcrypt.hashpw('${DHIS2_ADMIN_PWD}'.encode(), bcrypt.gensalt(prefix=b'2a')).decode())")
envsubst <adminpwd.sql | spoc-container exec dhis2-postgres -- psql dhis2

# Stop services required for setup
spoc-container stop dhis2-postgres

# Register application
vmmgr register-app dhis2 dhis2 "${DHIS2_ADMIN_USER}" "${DHIS2_ADMIN_PWD}"
