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


##
## 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
            users)
                user_conf=$(make_users_config "$value") || exit 1
                e "$user_conf" | ini_merge
                ;;
            acl)
                yaml_key_val_str "$key" "$value" | ini_merge
                ;;
            *)
                err "Unknown key '$key' in options."
                exit 1
                ;;
        esac
    done < <(e "$options" | shyaml key-values-0)
fi


## XXXvlab: ports should be not repeated (is repeated in charm metadata, or docker image)
ini_merge <<EOF
server:
  addr: ":5001"
EOF


ini_merge <<EOF
token:
  issuer: "Acme auth server"
  expiration: 900
EOF

## Can be modified by web-proxy relation
echo "http://$SERVICE_NAME:5001" > "$SERVICE_CONFIGSTORE/etc/docker-auth/realm"