#!/bin/sh
set -ev

# Volumes
POSTGRES_DATA="${VOLUMES_DIR}/gnuhealth/postgres_data"
GNUHEALTH_CONF="${VOLUMES_DIR}/gnuhealth/gnuhealth_conf"

# Create Postgres instance
install -o 105432 -g 105432 -m 700 -d ${POSTGRES_DATA}
spoc-container exec gnuhealth-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 GNUHEALTH_PWD=$(head -c 18 /dev/urandom | base64 | tr -d '+/=')
spoc-container start gnuhealth-postgres
envsubst <createdb.sql | spoc-container exec gnuhealth-postgres -- psql

# Configure GNU Health
install -o 108080 -g 108080 -m 750 -d ${GNUHEALTH_CONF}
envsubst <gnuhealth_conf/trytond.conf | install -o 108080 -g 108080 -m 640 /dev/stdin ${GNUHEALTH_CONF}/trytond.conf

# Populate database
export GNUHEALTH_ADMIN_USER="admin"
export GNUHEALTH_ADMIN_EMAIL="admin@example.com"
export GNUHEALTH_ADMIN_PWD=$(head -c 12 /dev/urandom | base64 | tr -d '+/=')
spoc-container exec gnuhealth -- sh -c "echo ${GNUHEALTH_ADMIN_PWD} >/tmp/.adminpwd; TRYTONPASSFILE=/tmp/.adminpwd trytond-admin -d gnuhealth --email ${GNUHEALTH_ADMIN_EMAIL} --all -v; rm /tmp/.adminpwd"

# Populate demo database
spoc-container exec gnuhealth -- zcat /srv/gnuhealth/gnuhealth_demo.sql.gz | spoc-container exec gnuhealth-postgres -- sh -c "PGPASSWORD=${GNUHEALTH_PWD} psql gnuhealth_demo gnuhealth"

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

# Register application
vmmgr register-app gnuhealth gh "${GNUHEALTH_ADMIN_USER}" "${GNUHEALTH_ADMIN_PWD}"
