#!/bin/sh
set -e

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

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

# Build Docker container
docker build -t sahana $(realpath $(dirname "${0}"))/sahana
cp ${SOURCE_DIR}/etc/init.d/sambro /etc/init.d/sambro
rc-update -u

# Create PostgreSQL user and database
export SAMBRO_PWD=$(head -c 18 /dev/urandom | base64)
envsubst <${SOURCE_DIR}/createdb.sql | docker exec -i postgres psql

# Prepare persistent directory structure
mkdir -p /srv/sambro/conf /srv/sambro/data/databases /srv/sambro/data/uploads /srv/sambro/data/SAMBRO
chown -R 8001:8001 /srv/sambro/conf /srv/sambro/data
docker run --rm -v /srv/sambro/conf:/mnt/conf sahana cp -rp /srv/web2py/applications/eden/models/. /mnt/conf
docker run --rm -v /srv/sambro/data/SAMBRO:/mnt/data sahana cp -rp /srv/web2py/applications/eden/modules/templates/SAMBRO/. /mnt/data

# Configure SAMBRO
export SAMBRO_HMAC=$(head -c 18 /dev/urandom | base64)
export SAMBRO_ADMIN_USER=admin@example.com
export SAMBRO_ADMIN_PWD=$(head -c 12 /dev/urandom | base64)
envsubst <${SOURCE_DIR}/srv/sambro/conf/000_config.py >/srv/sambro/conf/000_config.py
envsubst <${SOURCE_DIR}/masterUsers.csv >/tmp/masterUsers.csv
cp ${SOURCE_DIR}/srv/sambro/conf/00_settings.py /srv/sambro/conf/00_settings.py
cp ${SOURCE_DIR}/srv/sambro/data/SAMBRO/config.py /srv/sambro/data/SAMBRO/config.py
vmmgr update-login sambro "${SAMBRO_ADMIN_USER}" "${SAMBRO_ADMIN_PWD}"

# Populate database
docker run --rm -h sambro --link postgres -v /srv/sambro/conf:/srv/web2py/applications/eden/models -v /srv/sambro/data/SAMBRO:/srv/web2py/applications/eden/modules/templates/SAMBRO -v /tmp/masterUsers.csv:/srv/web2py/applications/eden/modules/templates/default/users/masterUsers.csv -v /srv/sambro/data/databases:/srv/web2py/applications/eden/databases sahana su - sahana -c "./web2py.py -S eden -M -R applications/eden/static/scripts/tools/noop.py"
rm /tmp/masterUsers.csv

# Set "production values" (increases performance) only if the DEBUG environment variable is not set
if [ ${DEBUG:-0} -eq 0 ]; then
    sed -i 's/settings.base.migrate = True/settings.base.migrate = False/' /srv/sambro/conf/000_config.py
    sed -i 's/settings.base.debug = True/settings.base.debug = False/' /srv/sambro/conf/000_config.py
    sed -i 's/#settings.base.prepopulate = 0/settings.base.prepopulate = 0/' /srv/sambro/conf/000_config.py
fi

# Stop services required for build
service postgres stop
