#!/bin/bash

set -e

# Copyright (C) 2018 Mike Gabriel <mike.gabriel@das-netzwerkteam.de>
#
# This script 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; either version 2 of the License, or
# (at your option) any later version.
#
# This script 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

if [ $(id -u) -gt 0 ]; then
	echo "ERROR: This script has to run as super-user root."
	exit 1
fi

LTSP_OPT="/srv/ltsp"

# work around libpam-tmpdir not working for the
# root user and /tmp being too small anyway...
TMPDIR="/srv/tmp"
export TMPDIR
mkdir -p ${TMPDIR}/
chown root:root ${TMPDIR}
chmod 1777 ${TMPDIR}

# Prep LTSP configuration
if [ -e "/etc/ltsp/ltsp.conf.itzks-systems-disklserver.in" ] && cat "/etc/ltsp/ltsp.conf.itzks-systems-disklserver.in" | grep -v "#" | grep -q "@rootpw@"; then

	# Drop previous ltsp.conf (yes, we want to do that!)
	rm -f /etc/ltsp/ltsp.conf
	touch /etc/ltsp/ltsp.conf
	chown root:root /etc/ltsp/ltsp.conf
	chmod 0600 /etc/ltsp/ltsp.conf

	echo "# THIS FILE IS RE-CREATED DAILY FROM /etc/ltsp/ltsp.conf.itzks-systems-disklserver.in - DON'T EDIT THIS FILE" >> /etc/ltsp/ltsp.conf
	echo >> /etc/ltsp/ltsp.conf

	# configure LTSP before creating ltsp.img and iPXE config
	host_rootpw=$(cat /etc/shadow | grep -E "^root:" | cut -d":" -f2)
	[ "$host_rootpw" ] && export host_rootpw && perl -p -e "s/\@rootpw\@/\$ENV{host_rootpw}/g" "/etc/ltsp/ltsp.conf.itzks-systems-disklserver.in" >> "/etc/ltsp/ltsp.conf"
	unset host_rootpw
fi

# Prep X2Go configuration (and pre the chroot, as well)
if [ -e "/etc/ltsp/x2gothinclient-settings.conf" ]; then
	. "/etc/ltsp/x2gothinclient-settings.conf"

	# FIXME: check for more than one chroot...
	TC_FLAVOUR="${TC_FLAVOUR:-minidesktop}"
	TC_DISTRO_CODENAME="${TC_DISTRO_CODENAME:-bullseye}"
	TC_DISTRO_ARCH="${TC_DISTRO_ARCH:-amd64}"
	TC_CHROOT="${TC_CHROOT:-/srv/ltsp/x2go-${TC_FLAVOUR}+${TC_DISTRO_ARCH}+${TC_DISTRO_CODENAME}}"
	TC_CONFIG="${TC_CONFIG:-/etc/ltsp/settings_x2go-${TC_FLAVOUR}+${TC_DISTRO_ARCH}+${TC_DISTRO_CODENAME}}"

	if [ -e "${TC_CHROOT}" ]; then

		echo "Installing X2Go TCE configuration into chroot environment..."

		mkdir -p "$TC_CHROOT/etc/x2go/"

		ls "$TC_CONFIG/x2gothinclient_init.d/" | while read init_part; do
			mkdir -p "$TC_CHROOT/etc/x2go/x2gothinclient_init.d/"
			if test -f "$TC_CONFIG/x2gothinclient_init.d/$init_part"; then
				cp -v "$TC_CONFIG/x2gothinclient_init.d/$init_part" "$TC_CHROOT/etc/x2go/x2gothinclient_init.d/"
				chmod a+rx "$TC_CHROOT/etc/x2go/x2gothinclient_init.d/$init_part"
			fi
		done

		if test -f "$TC_CONFIG/x2gothinclient-${TC_FLAVOUR}_start"; then
			cp -v "$TC_CONFIG/x2gothinclient-${TC_FLAVOUR}_start" "$TC_CHROOT/etc/x2go/x2gothinclient-${TC_FLAVOUR}_start"
			chmod a+rx "$TC_CHROOT/etc/x2go/x2gothinclient-${TC_FLAVOUR}_start"
		fi

		if test -f "$TC_CONFIG/x2gothinclient_sessions"; then
			cp -v "$TC_CONFIG/x2gothinclient_sessions" "$TC_CHROOT/etc/x2go/x2gothinclient_sessions"
			chmod a+rx "$TC_CHROOT/etc/x2go/x2gothinclient_sessions"
		fi

		if test -f "$TC_CONFIG/x2gothinclient-${TC_FLAVOUR}_background.svg"; then
			rm "$TC_CHROOT/etc/x2go/x2gothinclient-${TC_FLAVOUR}_background.svg"
			cp -v "$TC_CONFIG/x2gothinclient-${TC_FLAVOUR}_background.svg" "$TC_CHROOT/etc/x2go/x2gothinclient-${TC_FLAVOUR}_background.svg"
			ln -sf "/etc/x2go/x2gothinclient-${TC_FLAVOUR}_background.svg" "$TC_CHROOT/etc/x2go/x2gothinclient-background.svg"
		fi

		if test -f "$TC_CONFIG/freerdp/known_hosts" || test -f "$TC_CONFIG/freerdp/known_hosts2" ; then
			mkdir -p "$TC_CHROOT/etc/x2go/freerdp/"
			cp -v "$TC_CONFIG"/freerdp/known_hosts* "$TC_CHROOT/etc/x2go/freerdp/"
		fi
	fi
fi

# update (rebuild) squashfs images
ltsp_chroots="$(ls "${LTSP_OPT}" | while read chroot_dir; do test ! -h "${LTSP_OPT}/${chroot_dir}" -a -x "${LTSP_OPT}/${chroot_dir}/bin/bash" && echo -n "${chroot_dir} " || true; done)"
ltsp_chroots="${ltsp_chroots%%?*( )}"

for chroot in ${ltsp_chroots}; do

	if [ -e "${LTSP_OPT}/${chroot}/chroot-upgrade-in-process" ]; then
		echo "Chroot ${LTSP_OPT}/${chroot} is currently being upgraded. Skipping..."
		continue
	fi

	latest_upgrade=$(ls ${LTSP_OPT}/${chroot} | grep -E 'chroot-updated_[0-9]{8}$' | sort | tail -n1)

	if [ -z "${latest_upgrade}" ]; then
		echo "chroot ${LTSP_OPT}/${chroot} lacks the chroot-updated_<date> file. Can't proceeed. Skipping..."
		continue
	fi

	# several chroot preparations (also helpful when directly booting the nfsroot)...

	# These preparations run with every script execution (i.e. daily via CRON) to make sure the
	# NFS chroot is updated.

	# Copy an appropriate SSH secret key for DLWs to ${LTSP_OPT}/${chroot}/root/.ssh/id_<crypto>.
	# Currently we prefer disklserver:/root/.ssh/id_<crypto>.DLW and fall back to the host's private key file
	# (i.e. disklserver:/root/.ssh/id_<crypto>).
	for priv_key_file in id_ecdsa id_ecdsa_sk id_ed25519 id_ed25519_sk id_rsa; do

		if [ -e "/root/.ssh/${priv_key_file}.DLW" ] && [ ! -e "${LTSP_OPT}/${chroot}/root/.ssh/${priv_key_file}" ]; then
			mkdir -p "${LTSP_OPT}/${chroot}/root/.ssh/"
			cp "/root/.ssh/${priv_key_file}.DLW" "${LTSP_OPT}/${chroot}/root/.ssh/${priv_key_file}"
		elif [ -e "/root/.ssh/${priv_key_file}" ] && [ ! -e "${LTSP_OPT}/${chroot}/root/.ssh/${priv_key_file}" ]; then
			mkdir -p "${LTSP_OPT}/${chroot}/root/.ssh/"
			cp "/root/.ssh/${priv_key_file}" "${LTSP_OPT}/${chroot}/root/.ssh/${priv_key_file}"
		fi

	done

	# Copy an appropriate SSH known_hosts key file DLWs to ${LTSP_OPT}/${chroot}/root/.ssh/known_hosts.
	# Currently we prefer disklserver:/root/.ssh/known_hosts.DLW and fall back to the host's known_hosts file
	# (i.e. disklserver:/root/.ssh/known_hosts).
	if [ -e "/root/.ssh/known_hosts.DLW" ] && [ ! -e "${LTSP_OPT}/${chroot}/root/.ssh/known_hosts" ]; then
		mkdir -p "${LTSP_OPT}/${chroot}/root/.ssh/"
		cp "/root/.ssh/known_hosts.DLW" "${LTSP_OPT}/${chroot}/root/.ssh/"
	elif [ -e "/root/.ssh/known_hosts" ] && [ ! -e "${LTSP_OPT}/${chroot}/root/.ssh/known_hosts" ]; then
		mkdir -p "${LTSP_OPT}/${chroot}/root/.ssh/"
		cp "/root/.ssh/known_hosts" "${LTSP_OPT}/${chroot}/root/.ssh/"
	fi

	# Copy the host's SSH host keys to the LTSP client chroot if it doesn't have any host keys
	host_keys="$(find /etc/ssh/ssh_host_*)"
	if [ -n "${host_keys}" ]; then
		for host_key in ${host_keys}; do
			cp "${host_key}" "${LTSP_OPT}/${chroot}/etc/ssh/"
		done
	fi

	# Copy the SSH authorized_keys file for DLWs to ${LTSP_OPT}/${chroot}/root/.ssh/authorized_keys (e.g. disklserver:/root/.ssh/authorized_keys)
	# Use host's authorized_keys file for granting DLW access via SSH as root without password
	if [ -e "/root/.ssh/authorized_keys" ] && [ ! -e "${LTSP_OPT}/${chroot}/root/.ssh/authorized_keys" ]; then
		mkdir -p "${LTSP_OPT}/${chroot}/root/.ssh/"
		cp "/root/.ssh/authorized_keys" "${LTSP_OPT}/${chroot}/root/.ssh/authorized_keys"
	fi

	# Create the SquashFS image (if an update is required)
	if [ -e "${LTSP_OPT}/${chroot}/${latest_upgrade}.squashfs-created" ]; then
		echo "chroot ${LTSP_OPT}/${chroot}'s squashfs image is up-to-date. Skipping..."
	else
		if ltsp image "${LTSP_OPT}/${chroot}"; then
			rm -f "${LTSP_OPT}/${chroot}/chroot-updated_*.squashfs-created"
			touch "${LTSP_OPT}/${chroot}/${latest_upgrade}.squashfs-created"
		fi
	fi 

done

# let's update kernel images, ltsp.img (LTSP initrd) and LTSP's iPXE
# boot menu configuration, just in case...
ALL_IMAGES=1 ltsp kernel
ltsp initrd
ltsp ipxe
