#!/usr/bin/env bash
# Create the two databases the stack cannot start without:
#
#   masterdb   operator control plane (nacef_control_plane)
#   nacef_tpl  golden tenant image, cloned on every Provision
#
# Not having nacef_tpl is exactly what produces:
#   "Base modèle « nacef_tpl » introuvable. Créez-la d'abord ..."
# because nacef_tenant.py:171 refuses to provision without it.
#
# Run once, after the stack is up. Re-running is refused rather than
# destructive: drop the database by hand if you really mean to rebuild it.
set -Eeuo pipefail

DEPLOY_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$DEPLOY_DIR"
set -a; . ./.env; set +a

DC="docker compose -f $DEPLOY_DIR/docker-compose.yml"
TENANT_MODULES="nacef_pos,nacef_cockpit,nacef_theme"
CP_MODULES="nacef_control_plane"

exists() {
  [[ "$($DC exec -T db psql -U "$DB_USER" -d postgres -tAc \
        "SELECT 1 FROM pg_database WHERE datname='$1';" </dev/null)" == "1" ]]
}

# A database can exist and still be useless to us: starting the control-plane
# container with `-d masterdb` makes Odoo create the database and install only
# `base`. Existence alone is therefore not proof the stack is installed.
has_nacef_modules() {
  [[ "$($DC exec -T db psql -U "$DB_USER" -d "$1" -tAc \
        "SELECT count(*) FROM ir_module_module
          WHERE state='installed' AND name LIKE 'nacef%';" </dev/null 2>/dev/null \
        || echo 0)" -gt 0 ]]
}

install_db() {  # install_db <db> <modules>
  local db="$1" mods="$2"
  if exists "$db"; then
    if has_nacef_modules "$db"; then
      echo "==> $db already has the NACEF modules, leaving it alone"
      return 0
    fi
    echo "==> $db exists but has no NACEF modules (Odoo auto-created it on"
    echo "    first start); installing $mods into it"
  else
    echo "==> Creating $db with $mods"
  fi
  # --without-demo=all matters for nacef_tpl: demo records would be cloned
  # into every tenant and end up in fiscal archives.
  $DC run --rm --no-deps -T odoo \
    odoo -c /etc/odoo/odoo.conf -d "$db" -i "$mods" \
         --without-demo=all --stop-after-init </dev/null
}

# The control plane serves masterdb; installing into a database it is holding
# open leaves the running registry stale. Take the web tier down for this.
$DC up -d db
$DC stop odoo odoo-cp 2>/dev/null || true
until $DC exec -T db pg_isready -U "$DB_USER" >/dev/null 2>&1; do sleep 1; done

install_db masterdb  "$CP_MODULES"
install_db nacef_tpl "$TENANT_MODULES"

# The template must stay connection-free: CREATE DATABASE ... TEMPLATE fails
# if anything is attached. dbfilter ^%d$ already makes it unreachable over
# HTTP (an underscore is not a legal hostname character), so this is only a
# guard against someone connecting by hand.
$DC exec -T db psql -U "$DB_USER" -d postgres -c \
  "ALTER DATABASE nacef_tpl ALLOW_CONNECTIONS true;" >/dev/null

$DC up -d

cat <<'EOF'

Done. Verify from the control plane container:

  docker compose exec odoo-cp odoo shell -d masterdb --stop-after-init <<'PY'
  print(env['ir.config_parameter'].sudo().get_param('nacef.tenant_template'))
  PY

If it prints something other than nacef_tpl, either rename the database or
set the parameter (Settings > Technical > System Parameters).
EOF
