#!/bin/bash
## Should be executable N time in a row with same result.

. lib/common

set -e

if ! admin_backend=$(options-get "lokapi-host" 2>/dev/null) || [ -z "$admin_backend" ]; then

    if ! service:traverse "${SERVICE_NAME}":odoo-server >/dev/null; then
        err "Monujo requires either a ${WHITE}lokapi-host${NORMAL} option set,"
        echo "  or a ${DARKCYAN}odoo-server${NORMAL} relation satisfied." >&2
        exit 1
    fi
    if ! url=$(relation:get "${SERVICE_NAME}":odoo-server:web-proxy url); then
        err "Monujo doesn't support odoo-server not having a web-proxy yet."
        exit 1
    fi

    monujo:config_merge "{
        \"lokapiHost\": \"$url\"
    }"

    if ! dbname=$(options-get "lokapi-db" 2>/dev/null) || [ -z "$dbname" ]; then
        if ! dbname=$(relation:get "${SERVICE_NAME}":odoo-server dbname) || [ -z "$dbname" ]; then
            err "Can't find db name of our ${DARKCYAN}odoo-server${NORMAL} relation."
            if ! dbname=$(relation:get "${SERVICE_NAME}":odoo-server:postgres-database dbname) || [ -z "$dbname" ]; then
                err "Can't find db name of ${DARKCYAN}odoo-server${NORMAL}-->${DARKCYAN}postgres-database${NORMAL} relation."
                exit 1
            fi
        fi
        monujo:config_merge "{
            \"lokapiDb\": \"$dbname\"
        }"

    fi

fi


if ! map_url=$(options-get "map-url" 2>/dev/null) || [ -z "$map_url" ] ; then

    if map_url=$(relation:get "${SERVICE_NAME}":map-server:publish-dir url); then
        monujo:config_merge "{
          \"mapUrl\": \"$map_url\"
        }"
    fi
fi