#!/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

set -e

## The image runs as the unprivileged "carbone" user, while the datastore
## and configstore bind mounts are created by root.  Both /app/template
## (templates + metadata.db) and /app/config (config.json, keys, license)
## must be writable by that user, otherwise the container crash-loops with
## "EACCES: permission denied, open '/app/config/config.json'".
uid_gid=($(docker_get_uid_gid "$SERVICE_NAME" "carbone" "carbone")) || exit 1
uid="${uid_gid[0]}"
gid="${uid_gid[1]}"

mkdir -p "$SERVICE_DATASTORE/app/template" "$SERVICE_CONFIGSTORE/app/config"
chown "$uid:$gid" "$SERVICE_DATASTORE/app/template" "$SERVICE_CONFIGSTORE/app/config"

## Carbone starts in stateless mode (document generation only) and binds
## to 127.0.0.1 by default (see `carbone webserver --help`, v5.15.1).
## Inside Docker it must:
##  - listen on all interfaces so the web-proxy can reach it (CARBONE_BIND) ;
##  - serve the Studio web interface and /carbone-studio.js (CARBONE_STUDIO) ;
##  - enable stateful template management: stable 64-bit template IDs,
##    versioning and the GET/POST/PATCH /template endpoints
##    (CARBONE_TEMPLATE_MANAGEMENT).
##
## CARBONE_TEMPLATE_METADATA_FLUSH_CRON defaults to once a day; flushing
## every 5 minutes shrinks the window where a hard crash (SIGKILL, OOM)
## would lose template metadata.  The graceful-shutdown flush remains the
## safety net for redeploys (see docker-compose.stop_grace_period).
init-config-add "
$SERVICE_NAME:
  environment:
    CARBONE_BIND: \"0.0.0.0\"
    CARBONE_STUDIO: \"true\"
    CARBONE_TEMPLATE_MANAGEMENT: \"true\"
    CARBONE_TEMPLATE_METADATA_FLUSH_CRON: \"*/5 * * * *\"
"