#!/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 'Please run with sudo.' >&2
	exit 1
fi
if grep -q '^PasswordAuthentication no' "$conf" 2>/dev/null; then
	echo 'SSH password login is already turned off.'
	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 'No SSH key found (authorized_keys of root or a user). Run ssh-copy-id first, then try again; without a key you lock yourself out. --force overrides this.' >&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 'SSH password login is turned off. Test a new login with your key before closing this session.'
