#!/bin/sh
set -ev

# Volumes
POSTGRES_DATA="${VOLUMES_DIR}/odoo/postgres_data"
ODOO_CONF="${VOLUMES_DIR}/odoo/odoo_conf"
ODOO_DATA="${VOLUMES_DIR}/odoo/odoo_data"

# Create Postgres instance
install -o 105432 -g 105432 -m 700 -d ${POSTGRES_DATA}
spoc-container exec odoo-postgres -- initdb -D /var/lib/postgresql

# Configure Postgres
install -o 105432 -g 105432 -m 600 postgres_data/postgresql.conf ${POSTGRES_DATA}/postgresql.conf
install -o 105432 -g 105432 -m 600 postgres_data/pg_hba.conf ${POSTGRES_DATA}/pg_hba.conf

# Create databases
export ODOO_PWD=$(head -c 18 /dev/urandom | base64 | tr -d '+/=')
spoc-container start odoo-postgres
envsubst <createdb.sql | spoc-container exec odoo-postgres -- psql

# Configure Odoo
export ODOO_ADMIN_USER="admin"
export ODOO_ADMIN_PWD=$(head -c 12 /dev/urandom | base64 | tr -d '+/=')
install -o 108080 -g 108080 -m 750 -d ${ODOO_CONF}
install -o 108080 -g 108080 -m 750 -d ${ODOO_DATA}
envsubst <odoo_conf/odoo.conf | install -o 108080 -g 108080 -m 640 /dev/stdin ${ODOO_CONF}/odoo.conf

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

# Update admin account
export ODOO_ADMIN_HASH=$(spoc-container exec odoo -- python -c "from passlib.hash import pbkdf2_sha512;print(pbkdf2_sha512.hash('${ODOO_ADMIN_PWD}'))")
envsubst <adminpwd.sql | spoc-container exec odoo-postgres -- psql odoo

# Stop services required for setup
spoc-container stop odoo-postgres

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