#!/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``.
##  - use actions of other side for other side's business logic

. lib/common


if [ -z "$RELATION_DATA_FILE" ]; then
    err "$FUNCNAME: relation does not seems to be correctly setup."
    exit 1
fi

if ! [ -r "$RELATION_DATA_FILE" ]; then
    err "$FUNCNAME: can't read relation's data." >&2
    exit 1
fi


if [ "$(cat "$RELATION_DATA_FILE" | shyaml get-type)" == "str" ]; then
    ## Cached version already there

    ## Note that we rely on the fact that when the relations
    ## options are changed in the `compose.yml` file, the relation
    ## data file is recreated from the values of the
    ## `compose.yml`.
    info "Previous relation data is still valid."
    exit 0
fi

schedule=$(relation-get schedule) || true
exclude_dbs=$(relation-get exclude-dbs 2>/dev/null) || true
exclude_dbs=$(echo "$exclude_dbs" | shyaml get-values 2>/dev/null |
                  nspc) || true

lock_opts=(-D -p 10)


command=(
    docker run --rm
    -u 0
    -e MONGO_HOST=${SERVICE_NAME}
    -e exclude_dbs="$exclude_dbs"
    --network ${PROJECT_NAME}_default
    -v "$HOST_CHARM_STORE/${CHARM_REL_PATH#${CHARM_STORE}/}/resources/bin/mongo-backup:/usr/sbin/mongo-backup"
    -v "$SERVICE_DATASTORE/var/backups/mongo:/var/backups/mongo"
    --entrypoint mongo-backup
    "$DOCKER_BASE_IMAGE"
)

quoted_command=()
for arg in "${command[@]}"; do
    quoted_command+=("$(printf "%q" "$arg")")
done

printf "(%s) {%s} %s\n" \
       "$schedule" \
       "${lock_opts[*]}" \
       "${quoted_command[*]}" > "$RELATION_DATA_FILE"