#!/bin/sh
# sshstart - Start SSHD and set a password (if necessary)

# Copyright (C) 2001, Klaus Knopper <knopper@knopper.net>
# Copyright (C) 2004, Joerg Schirottke <master@kanotix.com>
# Copyright (C) 2004-2024, Stefan Lippers-Hollmann <s.l-h@gmx.de>
# Copyright (C) 2007-2024, Kel Modderman <kelvmod@gmail.com>

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2 of the
# License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# override tool behaviour through distro-defaults
FLL_LIVE_USER="aptosid"
if [ -s /etc/default/distro ]; then
	. /etc/default/distro
fi

if [ "$(id -u)" -ne 0 ]; then
	[ -x "$(which pkexec)" ] && exec pkexec $0 $@
	printf "ERROR: $0 needs root capabilities, please start it as root.\n\n" >&2
	exit 1
fi

if [ ! -x /etc/init.d/ssh ] && [ ! -x /usr/lib/systemd/system/ssh.service ]; then
	echo "openssh-server is not installed, aborting."
	exit 2
fi

if pgrep -x sshd >/dev/null; then
	echo "openssh-server is already running, aborting."
	exit 3
fi

# Rely on openssh-server's postinst to generate host keys.  Drop its stderr:
# the deb-systemd-invoke step warns that the still-disabled ssh units are
# "not starting", which is expected here (we start ssh ourselves below) and
# only confuses the user; the host key output on stdout is kept.
dpkg-reconfigure --frontend=noninteractive openssh-server 2>/dev/null

# Start the daemon.  systemctl starts the unit even though it is disabled
# (disabled only affects autostart at boot).
if ! service ssh start; then
	echo "openssh-server failed to start, aborting." >&2
	exit 4
fi

until ! grep -q "^$FLL_LIVE_USER:\*:" /etc/shadow; do
	echo ""
	echo "Set password for user '$FLL_LIVE_USER'"
	passwd "$FLL_LIVE_USER"
done

# Confirm what is running and how to reach it, so the user is not left
# guessing whether the server actually came up.
PORTS="$(/usr/sbin/sshd -T 2>/dev/null | awk 'tolower($1) == "port" { print $2 }' | paste -sd' ' -)"
[ -n "$PORTS" ] || PORTS=22

echo ""
if pgrep -x sshd >/dev/null 2>&1; then
	echo "SSH server is up and listening on port(s): ${PORTS}"

	ADDRS="$(hostname -I 2>/dev/null)"
	if [ -n "$ADDRS" ]; then
		echo "Connect to this machine with:"
		for ADDR in $ADDRS; do
			echo "    ssh -p ${PORTS%% *} ${FLL_LIVE_USER}@${ADDR}"
		done
	fi
else
	echo "Warning: sshd does not appear to be running." >&2
fi

echo ""
echo -n "Finished. Press Enter to exit."
read DUMMY

exit 0
