#!/bin/sh

# Copyright (C) 2010-2023 Pädagogisches Landesinstitut Rheinland-Pfalz
# Copyright (C) 2022-2023 Mike Gabriel <mike.gabriel@das-netzwerkteam.de>
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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.
#
# 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.

# Tar up the FAI config space of the Debian Edu Router.
#
# This script theoretically is able to handle different config
# spaces for different distribution versions.

set -ex

LC_ALL=C
export LC_ALL

product="$(echo $(basename $0) | sed -Ee "s/(.+)-fai_mkconfigspacetarball/\1/")"

###
### FAI Setup
###

# source debian-edu-fai's config file
# Allow site specific overrides to the variables
if [ -f /etc/debian-edu/${product}-fai.conf ] ; then
	. /etc/debian-edu/${product}-fai.conf
fi

[ "$archs" ]            || archs=$(command -V dpkg 1>/dev/null 2>/dev/null && dpkg --print-architecture || uname -m)
[ "$codenames" ]        || codenames=$(cat /etc/os-release | grep VERSION_CODENAME | cut -d "=" -f2)
[ "$rootpw" ]           || rootpw=""
[ "$fai_logserver" ]    || unset fai_logserver
[ "$fai_loguser" ]      || unset fai_loguser
[ "$school_tag" ]       || school_tag="SKOLE"

for codename in ${codenames}; do

	# skip codenames that don't sound like Debian suites...
	if ! echo "bullseye bookworm trixie forky sid unstable" | grep -q "${codename}"; then
		echo "WARNING: The name '${codename}' is not a known and recent Debian distribution codename. Skipping..."
		continue
	fi


	# iterate over configured FAI client architectures...
	for arch in ${archs}; do

		faiconfig="/etc/debian-edu/fai/${product}-fai.${arch}+${codename}"
		if [ ! -d ${faiconfig} ]; then
			echo "ERROR: FAI configuration ${faiconfig} not found, run ${product}_install script first."
			exit 1
		fi

		# source the NFS conf file... this might override our FAI_CONFIGDIR
		# (but should not as recommended in our nfsroot.conf.in template)
		if [ -f "$faiconfig/nfsroot.conf" ]; then
			. $faiconfig/nfsroot.conf
		else
			echo "ERROR: No nfsroot.conf file found in $faiconfig/, can't continue..."
			exit 1
		fi

		# hard-code some sensible defaults in case they have been commented out in $faiconfig/nfsroot.conf
		[ "$FAI_CONFIGDIR" ] || FAI_CONFIGDIR="/srv/fai/config"

		FAI_CONFIGDIR_REAL="${FAI_CONFIGDIR}"
		# if FAI_CONFIGDIR is a symlink, we need to find the real location...
		if [ -h ${FAI_CONFIGDIR} ]; then
			FAI_CONFIGDIR_REAL="$(readlink ${FAI_CONFIGDIR})"
		fi

		set +x
		echo
		echo "###"
		echo "### Installing/updating FAI config space (this takes some time)"
		echo "### (codename: ${codename}, architecture: ${arch})"
		echo "###"
		${product}-fai_updateconfigspace "${FAI_CONFIGDIR_REAL}"
		set -x

		# Update variables to be customized in FAI config space

		# This code block might be executed on the same FAI_CONFIGDIR several times
		# (once per arch and codename).
		# This is a known issue and works as designed. People might have chosen to
		# use difference FAI_CONFIGDIR values for different environments and with
		# such a choice executing the below per arch and per codename makes sense.
		find ${FAI_CONFIGDIR_REAL} -name '*.in' | while read file_to_adapt; do

			cp ${file_to_adapt} ${file_to_adapt%.in}

			[ "$rootpw" ]             && export rootpw          && perl -p -e "s/^(#|)ROOTPW=.{0,1}\@rootpw\@.{0,1}\s*\$/ROOTPW=\'\$ENV{rootpw}\'\n/g" "${file_to_adapt%.in}" > "${file_to_adapt%.in}.new"                                     && mv "${file_to_adapt%.in}.new" "${file_to_adapt%.in}"
			[ "$fai_logserver" ]      && export fai_logserver   && perl -p -e "s/^(#|)LOGSERVER=.{0,1}\@fai_logserver\@.{0,1}\s*\$/LOGSERVER=\'\$ENV{fai_logserver}\'\n/g" "${file_to_adapt%.in}" > "${file_to_adapt%.in}.new"         && mv "${file_to_adapt%.in}.new" "${file_to_adapt%.in}"
			[ "$fai_loguser" ]        && export fai_loguser     && perl -p -e "s/^(#|)LOGUSER=.{0,1}\@fai_loguser\@.{0,1}\s*\$/LOGUSER=\'\$ENV{fai_loguser}\'\n/g" "${file_to_adapt%.in}" > "${file_to_adapt%.in}.new"                 && mv "${file_to_adapt%.in}.new" "${file_to_adapt%.in}"
			[ "$school_tag" ]         && export school_tag      && perl -p -e "s/\@SKOLE\@/\$ENV{school_tag}/g" "${file_to_adapt%.in}" > "${file_to_adapt%.in}.new" && mv "${file_to_adapt%.in}.new" "${file_to_adapt%.in}"

			chown root:root ${file_to_adapt}
			chmod 0600 ${file_to_adapt}

		done

		# Are we a Debian Edu Router Deployserver (apt-get install ${product}-deployserver)?
		if [ -d /var/lib/${product}-fai/config/ ]; then

			# Create backup of previous config space tarball...
			if [ -f /var/lib/${product}-fai/config/${product}_fai-configspace.${arch}+${codename}.tar.gz ]; then
				mv /var/lib/${product}-fai/config/${product}_fai-configspace.${arch}+${codename}.tar.gz \
				   /var/lib/${product}-fai/config/${product}_fai-configspace.${arch}+${codename}.tar.gz.old
			fi

			set -x
			# create FAI config space tarball for http download in /var/lib/${product}-fai/
			cd ${FAI_CONFIGDIR_REAL} && \
			tar  --mode=go=rX,u+rw,a-s \
			     --owner=0 --group=0 \
			     --numeric-owner \
			     -cvz `find . | grep -v ./.git/ | grep -v -E "/.*\.in$" | sort` \
			     -f /var/lib/${product}-fai/config/${product}_fai-configspace.${arch}+${codename}.tar.gz
		else
				echo "ERROR: Package ${product}-deployserver may not be installed, please install it first"
				exit 1
		fi

	done

done
