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

cd $(dirname $0)
source cron.sh

SOURCE=$1
SECTION="${CTRSS_DIR}/data/data-from-${SOURCE}"

if [ -d "${SECTION}" ]; then
    echo >&2 "Already set-up."
else

    # https://www.guyrutenberg.com/2014/01/14/restricting-ssh-access-to-rsync/
    cat <(echo -n 'command="/usr/bin/perl $HOME/bin/rrsync -ro ~/cron2rss/",no-agent-forwarding,no-port-forwarding,no-pty,no-user-rc,no-X11-forwarding ') \
        ~/.ssh/cron2rss-copy_data.pub | ssh $SOURCE \
        'set -e; read KEY_LINE; mkdir -p ~/bin; [ -f ~/bin/rrsync ] || ln -s /usr/share/doc/rsync-*/support/rrsync ~/bin/; ' \
        'grep "${KEY_LINE}" ~/.ssh/authorized_keys -q && echo "Key already installed." || echo "${KEY_LINE}">> ~/.ssh/authorized_keys'

    ./_new_cron.sh data-from $SOURCE
    mkdir "${SECTION}"
    crontab -e
fi