#!/bin/bash

set -e

# Copyright (C) 2022-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.

if [ "$FAI_ACTION" != "install" ] && [ "$CONVERT" != "true" ] ; then
    exit 0
fi

function do_d-e-r_preseed() {
	pkg="debian-edu-router-config"
	template="$1"
	type="$2"
	value="$3"
	echo $pkg $template $type "$value" | ${ROOTCMD} debconf-set-selections
}

#
# Class DEBIAN_EDU_ROUTER checks for presence of at least 2 NICs.
#
# We need to decide which other NIC (except from UPLINK_IFACE) shall
# be used for the internal Education network.

# Detect our default route (hinting to the uplink NIC)
uplink_iface=$(ip -4 route | grep -E "^default via" | sed -e "s/.*\ dev\ //" | awk '{print $1}')

fields="ID_NET_NAME_FROM_DATABASE ID_NET_NAME_ONBOARD ID_NET_NAME_SLOT ID_NET_NAME_PATH"
for field in ${fields}; do
	name="`udevadm info /sys/class/net/${uplink_iface} | sed -rn "s/^E: $field=(.+)/\1/p" | sed -s 's/\s+//g'`"
	if [[ "${name}" ]]; then
		uplink_iface="${name}"
		break
	fi
done

# If we can detect an uplink interface, then
if [ -n "${uplink_iface}" ]; then

	# Let's assume, uplink iface is the first network card
	if [ "${NIC_LABEL0}" = "${uplink_iface}" ]; then
		# ... then Education NIC will be the second network card.
		edu_iface="${NIC_LABEL1}"
	else
		# ... otherwise, uplink is not the first network card, so
		# let's choose NIC_LABEL0 as our internal Education NIC
		edu_iface="${NIC_LABEL0}"
	fi

	do_d-e-r_preseed "debian-edu-router-config/net-int-iface-education" "select" "${edu_iface}"

fi
