#! /bin/bash

# Copyright (C) 2001-2022 Thomas Lange <lange@informatik.uni-koeln.de>
# Copyright (C) 2022-2023 Pädagogisches Landesinstitut Rheinland-Pfalz
# Copyright (C) 2011-2018 Andreas B. Mundt <andi@debian.org>
# 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 3 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.

error=0; trap 'error=$(($?>$error?$?:$error))' ERR # save maximum error code

if ifclass GATEWAY; then
	exit 0
fi

if ifclass DHCPC && [ "$FAI_ACTION" = "install" ] || [ "$FAI_ACTION" = "dirinstall" ]
then
    cat > "$target/etc/systemd/network/80-dhcp.network" <<-EOF
## generated by FAI
[Match]
Name=en*

[Network]
DHCP=yes
EOF
    $ROOTCMD systemctl enable systemd-networkd
elif [ "$FAI_ACTION" = "install" ] || [ "$FAI_ACTION" = "dirinstall" ]
then
      [ -n "$IPADDR" ] && cat > "$target/etc/systemd/network/50-static.network" <<-EOF
## generated by FAI
[Match]
Name=${NIC_LABEL0}

[Network]
Address=$IPADDR
Gateway=$GATEWAYS
EOF
    $ROOTCMD systemctl enable systemd-networkd
    [ -n "$NETWORK" ] && echo "localnet $NETWORK" > "$target/etc/networks"
    if [ ! -L "$target/etc/resolv.conf" ] && [ -e /etc/resolv.conf ]; then
	cp -p /etc/resolv.conf "$target/etc"
    fi
fi

# here fcopy is mostly used, when installing a client for running in a
# different subnet than during the installation
fcopy -iUM /etc/resolv.conf
fcopy -iUM /etc/network/interfaces /etc/networks

exit $error
