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

image_id=$(service_base_image_id "$SERVICE_NAME") || {
    err "couldn't get image id of $SERVICE_NAME."
    exit 1
}

CONTROL_FILE="$SERVICE_CONFIGSTORE/etc/onlyoffice/.image_id"
if [ "$(cat "$CONTROL_FILE")" != "$image_id" ]; then
    ## first time we need to extract configuration from image
    rm -rf "$SERVICE_CONFIGSTORE/etc/onlyoffice"
    mkdir -p "$SERVICE_CONFIGSTORE/etc/onlyoffice"
    service_base_image_export_dir "$SERVICE_NAME" /etc/onlyoffice/documentserver "$SERVICE_CONFIGSTORE/etc/onlyoffice/"
    printf "%s" "$image_id" > "$CONTROL_FILE"
else
    ## probably not needed to regenerate fonts
    init-config-add "\
$MASTER_BASE_SERVICE_NAME:
  environment:
    GENERATE_FONTS: \"false\"
"
fi