#!/bin/sh

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

# Check prerequisites
docker image ls | grep -q postfix || $(realpath $(dirname "${0}"))/postfix.sh
docker image ls | grep -q postgres || $(realpath $(dirname "${0}"))/postgres.sh

# Build Docker container
docker build -t gnuhealth ${SOURCE_DIR}

# Create databases
export GNUHEALTH_PWD=$(head -c 18 /dev/urandom | base64 |  tr -d '/+=')
envsubst <${SOURCE_DIR}/createdb.sql | docker exec -i 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_PWD=$(head -c 12 /dev/urandom | base64)
echo ${GNUHEALTH_ADMIN_PWD} >/tmp/.adminpwd
docker run --rm -h gnuhealth --link postgres -v /srv/gnuhealth/conf:/srv/gnuhealth/gnuhealth/tryton/server/config -v /tmp/.adminpwd:/tmp/.adminpwd -e TRYTONPASSFILE=/tmp/.adminpwd gnuhealth /srv/gnuhealth/gnuhealth/tryton/server/trytond-4.2.9/bin/trytond-admin -d gnuhealth --all -v
rm -f /tmp/.adminpwd

# Populate demo database
wget http://health.gnu.org/downloads/postgres_dumps/gnuhealth-3.2rc1.sql.gz -O /tmp/gnuhealth_demo.sql.gz
zcat /tmp/gnuhealth_demo.sql.gz | docker exec -i -e PGPASSWORD=${GNUHEALTH_PWD} postgres psql gnuhealth_demo gnuhealth
rm -f /tmp/gnuhealth_demo.sql.gz

# Create GNU Health service
cp ${SOURCE_DIR}/etc/init.d/gnuhealth /etc/init.d/gnuhealth
rc-update add gnuhealth boot
service gnuhealth start

# Create nginx app definition
cp ${SOURCE_DIR}/etc/nginx/conf.d/gnuhealth.conf /etc/nginx/conf.d/gnuhealth.conf
service nginx reload

# Add portal application definition
portal-app-manager gnuhealth "https://{host}:8408/index.html" admin "${GNUHEALTH_ADMIN_PWD}"
portal-app-manager gnuhealth-clients -p clienturl "{host}:8008"