#!/usr/bin/env bash
set -e

if [ -z "${SOURCE}" ]; then
    echo >&2 "Source cannot be empty!"
    exit 1
fi

target_dir="data-${SOURCE}"
target="${CTRSS_DIR}/${target_dir}"

rsync -e "ssh -i $HOME/.ssh/cron2rss-copy_data" -za "${SOURCE}:data/" "${target}/" --delete

cd "${CTRSS_DIR}/data"

find -maxdepth 1 -name "*-${SOURCE}" -xtype l -delete

ls "${target}" |
while read task; do
    target_link="${task}-${SOURCE}"
    [ -e "${target_link}" ] || ln -s "${target}/${task}" "${target_link}"
done