#!/bin/bash

## When writing relation script, remember:
##  - they should be idempotents
##  - they can be launched while the dockers is already up
##  - they are launched from the host
##  - the target of the link is launched first, and get a chance to ``relation-set``
##  - both side of the scripts get to use ``relation-get``.

. lib/common

set -e

exclude_patterns=$(relation-get "exclude-patterns") || true
include_patterns=$(relation-get "include-patterns") || true
include_patterns=${include_patterns:-"- /"}

while read-0 pattern; do
    if [[ "$pattern" != /* ]]; then
        err "Invalid pattern '$pattern' provided as ${WHITE}exclude-pattern${NORMAL}, " \
            "in relation's options."
        exit 1
    fi
    echo "/$BASE_SERVICE_NAME$pattern"
done < <(e "$exclude_patterns" | shyaml get-values-0) >> "$RSYNC_EXCLUDE_PATTERNS"

while read-0 pattern; do
    if [[ "$pattern" != /* ]]; then
        err "Invalid pattern '$pattern' provided as ${WHITE}exclude-pattern${NORMAL}, " \
            "in relation's options."
        exit 1
    fi
    echo "/$BASE_SERVICE_NAME$pattern"
done < <(e "$include_patterns" | shyaml get-values-0) >> "$RSYNC_INCLUDE_PATTERNS"