#!/bin/sh
set -e

SOURCE_DIR=$(realpath $(dirname "${0}"))/setup

# Check prerequisites
[ ! -e /run/openrc/started/postgres ] && service postgres start && STOP_POSTGRES=1

# Create databases
export GNUHEALTH_PWD=$(head -c 18 /dev/urandom | base64 |  tr -d '/+=')
envsubst <${SOURCE_DIR}/createdb.sql | lxc-attach -u 5432 -g 5432 postgres -- psql

# Configure GNU Health
mkdir -p /srv/gnuhealth/conf/
envsubst <${SOURCE_DIR}/srv/gnuhealth/conf/trytond.conf >/srv/gnuhealth/conf/trytond.conf

# Populate database
export GNUHEALTH_ADMIN_USER="admin"
export GNUHEALTH_ADMIN_PWD=$(head -c 12 /dev/urandom | base64)
echo ${GNUHEALTH_ADMIN_PWD} >/var/lib/lxc/gnuhealth/gnuhealth/tmp/.adminpwd
lxc-execute gnuhealth -- sh -c 'TRYTONPASSFILE=/tmp/.adminpwd trytond-admin -d gnuhealth --all -v'
rm -f /var/lib/lxc/gnuhealth/gnuhealth/tmp/.adminpwd
vmmgr update-login gnuhealth "${GNUHEALTH_ADMIN_USER}" "${GNUHEALTH_ADMIN_PWD}"

# Populate demo database
wget http://health.gnu.org/downloads/postgres_dumps/gnuhealth-32-demo.sql.gz -O /tmp/gnuhealth_demo.sql.gz
zcat /tmp/gnuhealth_demo.sql.gz | lxc-attach -u 5432 -g 5432 postgres -- sh -c "PGPASSWORD=${GNUHEALTH_PWD} psql gnuhealth_demo gnuhealth"
rm -f /tmp/gnuhealth_demo.sql.gz

# Install service
cp ${SOURCE_DIR}/etc/init.d/gnuhealth /etc/init.d/gnuhealth
rc-update -u

# Stop services required for setup
[ ! -z ${STOP_POSTGRES} ] && service postgres stop
