#!/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 'Bitte mit sudo aufrufen.' >&2
	exit 1
fi
if grep -q '^PasswordAuthentication no' "$conf" 2>/dev/null; then
	echo 'Passwort-Anmeldung per SSH ist bereits abgeschaltet.'
	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 'Kein SSH-Schlüssel hinterlegt (authorized_keys von root oder einem Benutzer). Erst ssh-copy-id, dann erneut; ohne Schlüssel sperrt man sich aus. --force übergeht das.' >&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 'Passwort-Anmeldung per SSH ist abgeschaltet. Neue Anmeldung mit Schlüssel testen, bevor diese Sitzung geschlossen wird.'
