#! /bin/bash

# Copyright (C) 2001-2016 Thomas Lange <lange@informatik.uni-koeln.de>
# Copyright (C) 2010-2011 Michael Goetze <mgoetze@mgoetze.net>
# 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 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

# a list of modules which are loaded at boot time
for module in $MODULESLIST; do
    ainsl -a /etc/modules "^$module$"
done

fcopy -Mv /etc/hostname || echo "$HOSTNAME" > "$target/etc/hostname"
ainsl -a /etc/mailname "${HOSTNAME}"
if [ ! -e "$target/etc/adjtime" ]; then
    printf "0.0 0 0.0\n0\nUTC\n" > "$target/etc/adjtime"
fi
if [ "$UTC" = "yes" ]; then
    sed -i -e 's:^LOCAL$:UTC:' "$target/etc/adjtime"
else
    sed -i -e 's:^UTC$:LOCAL:' "$target/etc/adjtime"
fi

# enable linuxlogo
if [ -f "$target/etc/inittab" ]; then
    sed -i -e 's#/sbin/getty 38400#/sbin/getty -f /etc/issue.linuxlogo 38400#' "${target}/etc/inittab"
elif [ -f "$target/lib/systemd/system/getty@.service" ]; then
    sed -i -e 's#sbin/agetty --noclear#sbin/agetty -f /etc/issue.linuxlogo --noclear#' "$target/lib/systemd/system/getty@.service"
fi

# make sure a machine-id exists
if [ ! -f "$target/etc/machine-id" ]; then
   touch "$target/etc/machine-id"
fi
# recreate machine-id if the file is empty
if [ X"$(stat -c '%s' "$target/etc/machine-id" 2>/dev/null)"  = X0 ] && [ -f /bin/systemd-machine-id-setup ]; then
    $ROOTCMD systemd-machine-id-setup
fi

ln -fs /proc/mounts "$target/etc/mtab"

rm -f "$target/etc/dpkg/dpkg.cfg.d/fai" "$target/etc/dpkg/dpkg.cfg.d/unsafe-io"

if [ -d /etc/fai ]; then
    ainsl -a /etc/fai/fai.conf "FAI_CONFIG_SRC=$FAI_CONFIG_SRC"
    fcopy -Miv /etc/fai/fai.conf
fi
fcopy -iv /etc/rc.local

exit $error
