#!/bin/bash

set -euo pipefail

pubkeyfile="/root/.ssh/authorized_keys"
separator="# backup-borg-begin DO NOT EDIT UNDER THIS LINE"
mkdir -p "$DATA_DIR/pubkeys" "$DATA_DIR/.ssh"

# Create ssh key if not found
if [ ! -e "$DATA_DIR/.ssh/borg-client" ] ; then
    ssh-keygen -f "$DATA_DIR/.ssh/borg-client" -C "SSH key for backup trigger" -P ''
fi

# Remove separator and automated lines if found
if [ -n "$(grep "$separator" "$pubkeyfile")" ] ; then
	sed -i "/$separator/,//d" "$pubkeyfile"
fi

# Place separator back
echo "$separator" >> "$pubkeyfile"

# Foreach borg server key
while read serverkey ; do
	# Add authorized_keys line
	echo "command=\"$DOCKER_DIR/script-sauvegarde.sh $serverkey\" $(cat "$DATA_DIR/pubkeys/$serverkey")" >> "$pubkeyfile"
done < <(ls "$DATA_DIR/pubkeys")
