#!/bin/sh
set -eu
[ "${1:-}" = configure ] || exit 0
config=/etc/schipsave-web
key=$config/ssh/id_ed25519
install -d -m0755 "$config"
[ ! -L "$config/ssh" ] || exit 1
install -d -o root -g root -m0700 "$config/ssh"
[ ! -L "$key" ] && [ ! -L "$key.pub" ] || exit 1
if [ ! -e "$key" ]; then
    previous=$(getent passwd borg | cut -d: -f6)
    if [ -n "$previous" ] && [ -f "$previous/.ssh/id_ed25519" ]; then
        install -o root -g root -m0600 "$previous/.ssh/id_ed25519" "$key"
    else
        ssh-keygen -q -t ed25519 -N '' -f "$key"
    fi
fi
chown root:root "$key"
chmod 0600 "$key"
umask 077
ssh-keygen -y -f "$key" > "$key.pub"
chown root:root "$key.pub"
chmod 0644 "$key.pub"
# Existing workers and their SSH keys remain in use until a safe service restart.
exit 0
