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

## XXXvlab: should use container name here so that it could support
## multiple mysql
label=${SERVICE_NAME}-mysql-backup
DST=$CONFIGSTORE/$TARGET_SERVICE_NAME/etc/cron/$label
schedule=$(relation-get schedule)

if ! echo "$schedule" | egrep '^\s*(([0-9/,*-]+\s+){4,4}[0-9/,*-]+|@[a-z]+)\s*$' >/dev/null 2>&1; then
    err "Unrecognized schedule '$schedule'."
    exit 1
fi

## Warning: using '\' in heredoc will be removed in the final cron file, which
##   is totally wanted: cron does not support multilines.

## Warning: 'docker -v' will use HOST directory even if launched from
##   'cron' container.
file_put "$DST" <<EOF
COMPOSE_LAUNCHER_OPTS=$COMPOSE_LAUNCHER_OPTS

$schedule   root lock $label -D -p 10 -c "\
    docker run --rm \
        --network ${PROJECT_NAME}_default \
        -v \"$LOCAL_DB_PASSFILE\":/root/.my.cnf \
        -v \"$HOST_CHARM_STORE/${CHARM_REL_PATH#${CHARM_STORE}/}/resources/bin/mysql-backup:/usr/sbin/mysql-backup\" \
        -v \"$SERVICE_DATASTORE/var/backups/mysql:/var/backups/mysql\" \
        --entrypoint mysql-backup \
        \"$DOCKER_BASE_IMAGE\" --host \"${SERVICE_IMAGE}\"" 2>&1 | ts '\%F \%T \%Z' >> /var/log/cron/${label}_script.log
EOF
chmod +x "$DST"