#!/bin/sh
set -e

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

# 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 ${SOURCE_DIR}
cp ${SOURCE_DIR}/etc/init.d/sahana /etc/init.d/sahana
rc-update -u

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

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

# Copy Spotter template
cp -r ${SOURCE_DIR}/srv/sahana/data/Spotter /srv/sahana/data/
chown -R 8001:8001 /srv/sahana/data

# Configure Sahana
export SAHANA_HMAC=$(head -c 18 /dev/urandom | base64)
export SAHANA_ADMIN_USER=admin@example.com
export SAHANA_ADMIN_PWD=$(head -c 12 /dev/urandom | base64)
envsubst <${SOURCE_DIR}/srv/sahana/conf/000_config.py >/srv/sahana/conf/000_config.py
envsubst <${SOURCE_DIR}/srv/sahana/data/Spotter/masterUsers.csv >/srv/sahana/data/Spotter/masterUsers.csv
cp ${SOURCE_DIR}/srv/sahana/conf/00_settings.py /srv/sahana/conf/00_settings.py
vmmgr update-login sahana "${SAHANA_ADMIN_USER}" "${SAHANA_ADMIN_PWD}"

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

# 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/sahana/conf/000_config.py
    sed -i 's/settings.base.debug = True/settings.base.debug = False/' /srv/sahana/conf/000_config.py
    sed -i 's/#settings.base.prepopulate = 0/settings.base.prepopulate = 0/' /srv/sahana/conf/000_config.py
fi

# Stop services required for build
service postgres stop
