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


##
## This script has to replace `exclude-dbs` options to match definition
## from `schedule-command` interface that is awaited by the target side
## in the `pre_deploy` script.
##

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
    -e PGHOST=${SERVICE_NAME}
    --network ${PROJECT_NAME}_default
    -e exclude_dbs="$exclude_dbs"
    -v "$LOCAL_DB_PASSFILE":/root/.pgpass
    -v "$HOST_CHARM_STORE/${CHARM_REL_PATH#${CHARM_STORE}/}/resources/bin/pg-backup:/usr/sbin/pg-backup"
    -v "$SERVICE_DATASTORE/var/backups/pg:/var/backups/pg"
    --entrypoint pg-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"
    echo "data: '$(cat "$RELATION_DATA_FILE")'" >&2