#!/bin/sh
set -ev

cd $(realpath $(dirname "${0}"))/install

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

# Create databases
export ODOO_PWD=$(head -c 18 /dev/urandom | base64)
envsubst <createdb.sql | lxc-attach -u 5432 -g 5432 postgres -- psql

# Configure Odoo
export ODOO_ADMIN_USER="admin"
export ODOO_ADMIN_PWD=$(head -c 12 /dev/urandom | base64)
mkdir -p /srv/odoo10/conf/ /srv/odoo10/data/
chown 8019:8019 /srv/odoo10/data/
envsubst <srv/odoo10/conf/odoo.conf >/srv/odoo10/conf/odoo.conf

# Populate database
lxc-start odoo10 -- /srv/odoo/odoo-bin -c /srv/odoo/odoo.conf -i base --load-language=cs_CZ
until grep -q 'odoo.modules.loading: Modules loaded.' /var/log/lxc/odoo10.log; do
    sleep 1
done
lxc-stop odoo10

# Update admin account
export ODOO_ADMIN_HASH=$(lxc-execute odoo10 -- python -c "from passlib.hash import pbkdf2_sha512;print pbkdf2_sha512.encrypt('${ODOO_ADMIN_PWD}')")
envsubst <adminpwd.sql | lxc-attach -u 5432 -g 5432 postgres -- psql odoo10

# Install service
cp etc/init.d/odoo10 /etc/init.d/odoo10
rc-update -u

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

# Register application
vmmgr register-app odoo10 "${ODOO_ADMIN_USER}" "${ODOO_ADMIN_PWD}"

exit 0
