#!/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 'Eseguire con sudo.' >&2
	exit 1
fi
if grep -q '^PasswordAuthentication no' "$conf" 2>/dev/null; then
	echo 'L'"'"'accesso SSH con password è già disattivato.'
	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 'Nessuna chiave SSH trovata (authorized_keys di root o di un utente). Prima ssh-copy-id, poi riprovare; senza chiave si resta chiusi fuori. --force lo ignora.' >&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 'L'"'"'accesso SSH con password è disattivato. Provare un nuovo accesso con la chiave prima di chiudere questa sessione.'
