#!/bin/bash

## Should be executable N time in a row with same result.

set -e

VOLUMES=$(relation-get volumes 2>/dev/null)
GROUP=$(relation-get group 2>/dev/null) || true

if test "$GROUP" && ! getent group "$GROUP" >/dev/null 2>&1; then
    die "No group '$GROUP' found."
fi

config-add "\
$MASTER_TARGET_SERVICE_NAME:
  volumes:
$(while read-0 volume_def; do
    IFS=: read src dst mode < <(echo "$volume_def:")
    mode=${mode:-rw}
    if [ "$mode" == "rw" -a "$GROUP" ]; then
        debug setfacl -m "g:$GROUP:rwx" -R "$DATASTORE/$BASE_SERVICE_NAME$src"
        setfacl -m "g:$GROUP:rwx" -R "$DATASTORE/$BASE_SERVICE_NAME$src"
    fi
    echo "    - $DATASTORE/$BASE_SERVICE_NAME$src:$dst:$mode"
  done < <(echo "$VOLUMES" | shyaml get-values-0))"