#!/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
dpkg-reconfigure --frontend=noninteractive openssh-server

service ssh start

if [ "$?" -ne 0 ]; then
	echo "openssh-server failed to start, aborting."
	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

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

exit 0
