#!/bin/bash

## Init is run on host
## For now it is run every time the script is launched, but
## it should be launched only once after build.

## Accessible variables are:
## - SERVICE_NAME        Name of current service
## - DOCKER_BASE_IMAGE   Base image from which this service might be built if any
## - SERVICE_DATASTORE           Location on host of the DATASTORE of this service
## - SERVICE_CONFIGSTORE         Location on host of the CONFIGSTORE of this service


LIB="$SERVICE_DATASTORE/var/lib/odoo"

. lib/common

set -e

odoo_uid=$(get_odoo_uid)

mkdir -p "$LIB"
## XXXvlab: this one can fail if files are removed (from sessions dir)
find "$LIB" \! -user "$odoo_uid" -print0 | while read-0 f; do
    chown -v "$odoo_uid" "$f" || exit 1
done

## workers management
workers=$(options-get workers 2>/dev/null) || true
workers=${workers:-1}

modules=$(options-get modules 2>/dev/null | yaml_get_values ,) || true
if [ -z "$modules" ]; then
    modules=base
else
    modules="base,${modules}"
fi


## config file
conf=$(options-get conf 2>/dev/null) || true

CONFIGFILE="$SERVICE_CONFIGSTORE/etc/odoo/tecnativa.conf"
mkdir -p "${CONFIGFILE%/*}"
while read-0 section section_def; do
    debug "'$section' '$section_def'"
    printf "[%s]\n" "$section"
    while read-0 key val; do
        debug "'$key' '$val'"
        key_option=${key//-/_}
        printf "%s=%s\n" "$key_option" "$val"
    done < <(e "$section_def" | shyaml key-values-0)
done < <(e "$conf" | shyaml key-values-0) > "$CONFIGFILE"

if [ -s "$CONFIGFILE" ]; then
    init-config-add "
$SERVICE_NAME:
  volumes:
    - \"$CONFIGFILE:/opt/odoo/custom/conf.d/compose.conf:ro\"
"
fi

init-config-add "
$SERVICE_NAME:
  command:
    - \"--workers=${workers}\"
    - \"-i ${modules}\"
"