_match_key() {
	[ -e "/etc/ssh/$1" ] || return 1
	local _key_sha1
	_key_sha1="$(sha1sum "/etc/ssh/$1" | cut -d ' ' -f 1)"
	# Guard against empty or invalid keys - empty greps would return 0.
	if [ -z "$_key_sha1" ]; then
		return 1
	fi
	grep -q "$_key_sha1" "/usr/share/doc/openssh/revoked-keys/aosa-2017-0034/$1"
}

_match_all_keys() {
	for i in \
	    ssh_host_dsa_key ssh_host_dsa_key.pub ssh_host_ecdsa_key \
	    ssh_host_ecdsa_key.pub ssh_host_ed25519_key \
	    ssh_host_ed25519_key.pub ssh_host_rsa_key \
	    ssh_host_rsa_key.pub; do
		if _match_key $i; then
			return 0
		fi
	done
	return 1
}

_match_fingerprint() {
	[ -e "/etc/ssh/$1" ] || return 1
	local _key_fingerprint
	_key_fingerprint="$(ssh-keygen -l -E sha256 -f "/etc/ssh/$1" | cut -d' ' -f 2)"
	# Guard against empty or invalid keys - empty greps would return 0.
	if [ -z "$_key_fingerprint" ]; then
		return 1
	fi
	grep -q "$_key_fingerprint" \
		"/usr/share/doc/openssh/revoked-keys/revoked_hosts"
}

_match_all_fingerprints() {
	for i in \
	    ssh_host_dsa_key ssh_host_ecdsa_key ssh_host_ed25519_key \
	    ssh_host_rsa_key; do
		if _match_fingerprint $i; then
			return 0
		fi
	done
	return 1
}

# No need to reload daemon unless the host keys were refreshed (due to
# accidental leaks, etc.).
_host_key_refreshed=0

if \
	_match_all_keys || \
	_match_all_fingerprints; then
# Certain system media, images, and tarballs are known to contain leaked host
# keys. Revoke them.
	. /usr/share/debconf/confmodule
	db_get openssh/leaked_keys_20240913

	/usr/bin/rm -fv \
		/etc/ssh/ssh_host_dsa_key \
		/etc/ssh/ssh_host_dsa_key.pub \
		/etc/ssh/ssh_host_ecdsa_key \
		/etc/ssh/ssh_host_ecdsa_key.pub \
		/etc/ssh/ssh_host_ed25519_key \
		/etc/ssh/ssh_host_ed25519_key.pub \
		/etc/ssh/ssh_host_rsa_key \
		/etc/ssh/ssh_host_rsa_key.pub
	/usr/bin/ssh-keygen -A

	_host_key_refreshed=1
fi

echo -e "Checking whether systemd units need to be reload..."
if [[ $(systemctl show sshd --property=NeedDaemonReload | cut -d= -f2) == "yes" || \
      "$_host_key_refreshed" = "1" ]]; then
	echo "Reloading systemd units ..."
	systemctl daemon-reload
	echo "Restarting sshd service ..."
	systemctl try-restart sshd
else
	echo "Nothing needs reloading."
fi
