#!/bin/sh
# bashclub OS: Passwort-Anmeldung per SSH abschalten (bashclub-base)
set -eu
root=${BASHCLUB_ROOT:-}
conf=$root/etc/ssh/sshd_config.d/00-bashclub.conf
if [ -z "$root" ] && [ "$(id -u)" != 0 ]; then
	echo 'Voer uit met sudo.' >&2
	exit 1
fi
if grep -q '^PasswordAuthentication no' "$conf" 2>/dev/null; then
	echo 'Aanmelden via SSH met wachtwoord is al uitgeschakeld.'
	exit 0
fi
keys=0
for f in "$root"/root/.ssh/authorized_keys "$root"/home/*/.ssh/authorized_keys; do
	if [ -f "$f" ] && grep -qE '^(ssh-|ecdsa-|sk-)' "$f"; then keys=$((keys + 1)); fi
done
if [ "$keys" = 0 ] && [ "${1:-}" != --force ]; then
	echo 'Geen SSH-sleutel gevonden (authorized_keys van root of een gebruiker). Eerst ssh-copy-id, dan opnieuw; zonder sleutel sluit je jezelf buiten. --force negeert dit.' >&2
	exit 1
fi
mkdir -p "$(dirname "$conf")"
touch "$conf"
sed -i -e '/^PasswordAuthentication /d' -e 's/^# bashclub-install: .*/# bashclub-install: nur Schlüssel (bashclub-ssh-keyonly)/' "$conf"
echo 'PasswordAuthentication no' >>"$conf"
if [ -z "$root" ]; then
	sshd -t
	systemctl reload ssh
fi
echo 'Aanmelden via SSH met wachtwoord is uitgeschakeld. Test een nieuwe aanmelding met de sleutel voordat u deze sessie sluit.'
