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

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

private_key=$(options-get private-key) || exit 1
target=$(options-get target) || exit 1
ident=$(options-get ident) || exit 1

home=/var/lib/rsync
local_path_key=$home/.ssh
host_path_key="$SERVICE_CONFIGSTORE${local_path_key}"

echo "$private_key" | file_put "$host_path_key/id_rsa"
chmod 600 "$host_path_key/id_rsa"

label="${SERVICE_NAME}"
DST=$CONFIGSTORE/$TARGET_CHARM_NAME/etc/cron/$label

## Warning: using '\' in heredoc will be removed in the final cron file, which
##   is totally wanted: cron does not support multilines.
file_put "$DST" <<EOF
$schedule    root   lock $label -v -D -p 10 -k -c "\
    docker run --rm \
        -e LABEL_HOSTNAME=\"$ident\" \
        -v \"$RSYNC_CONFIG_DIR:/etc/rsync\" \
        -v \"$host_path_key:$local_path_key\" \
        -v \"$HOST_DATASTORE:/mnt/source\" \
        --network ${PROJECT_NAME}_default \
        \"$DOCKER_BASE_IMAGE\" \
        /mnt/source \"$target\"" 2>&1 | ts '\%F \%T' >> /var/log/cron/${label}_script.log
EOF
chmod +x "$DST"