#!/bin/bash
set -euo pipefail

source ./0.variables.env

CUSTOM_DIR="${CUSTOM_DIR:-./custom}"
CONTAINER_PREFIX="/mnt/extra-addons"
ODOO_CONF="${ODOO_CONF:-./odoo.conf.template}"

# Liste les sous-répertoires (1er niveau), trie, préfixe, joint avec virgules
SUBDIRS=$(
  find "$CUSTOM_DIR" -mindepth 1 -maxdepth 1 -type d \
       ! -name '.*' -printf '%f\n' \
  | sort \
  | sed "s|^|${CONTAINER_PREFIX}/|" \
  | paste -sd,
)

# Concatène /mnt/extra-addons (racine) + tous les sous-dirs
ADDONS_PATH="${CONTAINER_PREFIX},${SUBDIRS}"

# Remplace ou ajoute la ligne addons_path dans odoo.conf
if grep -qE "^[[:space:]]*#?[[:space:]]*addons_path[[:space:]]*=" "$ODOO_CONF"; then
    sed -i -E "s|^[[:space:]]*#?[[:space:]]*addons_path[[:space:]]*=.*|addons_path = ${ADDONS_PATH}|" "$ODOO_CONF"
else
    sed -i -E "/^\[options\]/a addons_path = ${ADDONS_PATH}" "$ODOO_CONF"
fi

echo "addons_path = ${ADDONS_PATH}"