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


# Please note that postgres detect on its own if its datadir needs to be populated


. lib/common


if ! [ -f "$HOST_CYCLOS_CONFIG" ]; then
    ## create cyclos.properties
    cyclos:build || exit 1
fi

if ! [ -f "$HOST_CYCLOS_CONFIG" ]; then
    err "No file '$HOST_CYCLOS_CONFIG'."
    return 1
fi

PROPS=(
    cyclos.header.remoteAddress X-Forwarded-For
    cyclos.header.protocol X-Forwarded-Proto
)

while read-0 label value; do
    sed -ri "s/^($label\s+=)\s*.*/\1 $value/g" "$HOST_CYCLOS_CONFIG" >&2
done < <(array_values_to_stdin PROPS)


init-config-add "
$SERVICE_NAME:
  environment:
    JAVA_OPTS: |
      -Dcyclos.cors.origin=*
      -Dcyclos.header.remoteAddress=X-Forwarded-For
      -Dcyclos.header.protocol=X-Forwarded-Proto
"