#!/bin/sh
set -ev

# Volumes
POSTGRES_DATA="${VOLUMES_DIR}/seeddms/postgres_data"
SEEDDMS_DATA="${VOLUMES_DIR}/seeddms/seeddms_data"
SEEDDMS_CONF="${VOLUMES_DIR}/seeddms/seeddms_conf"
SEEDDMS_LAYER="${LAYERS_DIR}/seeddms_6.0.14-210106"

# Create Postgres instance
install -o 105432 -g 105432 -m 700 -d ${POSTGRES_DATA}
spoc-container exec seeddms-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

# Copy existing files into persistent storage
cp -rp ${SEEDDMS_LAYER}/srv/seeddms/conf ${SEEDDMS_CONF}
cp -rp ${SEEDDMS_LAYER}/srv/seeddms/data ${SEEDDMS_DATA}

# Populate database
export SEEDDMS_PWD=$(head -c 18 /dev/urandom | base64 | tr -d '+/=')
spoc-container start seeddms-postgres
envsubst <createdb.sql | spoc-container exec seeddms-postgres -- psql
cat ${SEEDDMS_LAYER}/srv/seeddms/seeddms/install/create_tables-postgres.sql | spoc-container exec seeddms-postgres -- sh -c "PGPASSWORD=${SEEDDMS_PWD} psql seeddms seeddms"
cat custom.sql | spoc-container exec seeddms-postgres -- psql seeddms

# Configure SeedDMS
envsubst <seeddms_conf/settings.xml | install -o 108080 -g 108080 -m 640 /dev/stdin ${SEEDDMS_CONF}/settings.xml
export SEEDDMS_ADMIN_USER="admin"
export SEEDDMS_ADMIN_PWD=$(head -c 12 /dev/urandom | base64 | tr -d '+/=')
export SEEDDMS_ADMIN_EMAIL="admin@example.com"
envsubst <adminpwd.sql | spoc-container exec seeddms-postgres -- psql seeddms

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

# Register application
vmmgr register-app seeddms dms "${SEEDDMS_ADMIN_USER}" "${SEEDDMS_ADMIN_PWD}"
