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


. lib/common

set -e

if [ -e "$HOST_CONFIG_FILE" ]; then
    echo > "$HOST_CONFIG_FILE"
else
    mkdir -p "$(dirname "$HOST_CONFIG_FILE")"
    touch "$HOST_CONFIG_FILE"
fi

init-config-add "
$SERVICE_NAME:
  volumes:
    - $HOST_CONFIG_FILE:$CONFIG_FILE
"

ini_merge <<EOF || exit 1
version: 0.1
storage:
  filesystem:
    rootdirectory: /var/lib/docker-registry

http:
  addr: $SERVICE_NAME:5000
  net: tcp
  host: http://$SERVICE_NAME:5000
  ## XXXvlab: not used for now
  #secret: asecretforlocaldevelopment
  relativeurls: false
  # debug:
  #   addr: localhost:5001
  # headers:
  #   X-Content-Type-Options: [nosniff]
  # http2:
  #   disabled: false

EOF


##
## Merge compose options
##

service_def=$(get_compose_service_def "$SERVICE_NAME") || return 1
options=$(e "$service_def" | shyaml -y get-value "options") || true

if [ "$options" ]; then
    while read-0 key value; do
        case "$key" in
            auth|storage|middleware|reporting|http|redis|version)
                err "You should not configure '$key' in this charm."
                exit 1
                ;;
            log|loglevel|notifications|health|proxy|compatibility|validation)
                continue
                ;;
            *)
                err "Unknown key '$key' in options."
                exit 1
                ;;
        esac
    done < <(e "$options" | shyaml key-values-0)

    e "$options" | ini_merge || exit 1

fi