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

service_def=$(get_compose_service_def "$SERVICE_NAME")

keys=$(echo "$service_def" | shyaml get-value options.keys 2>/dev/null) || true

[ "$keys" ] || exit 0

local_path_key=/etc/rsync/keys
host_path_key="$SERVICE_CONFIGSTORE${local_path_key}"
key_nb=0

volume_keys=()
while read-0 key; do
    debug "Creating access key ${key_nb}" || true
    echo "$key" | file_put "$host_path_key/key_${key_nb}.pub"
    ((key_nb++)) || true
done < <(echo "$keys" | shyaml get-values-0)

volume_keys+=("$host_path_key:$local_path_key:ro")

init-config-add "\
$SERVICE_NAME:
  volumes:
    - $host_path_key:$local_path_key:ro
"