#!/bin/bash

build() {
    add_systemd_unit systemd-networkd.service

    # enable systemd-networkd.service
    add_symlink /etc/systemd/system/sysinit.target.wants/systemd-networkd.service \
                /usr/lib/systemd/system/systemd-networkd.service

    SD_NETWORK_CONFIG="${SD_NETWORK_CONFIG:-/etc/systemd/network}"
    if [[ ! -d "$SD_NETWORK_CONFIG" ]]; then
        error "${SD_NETWORK_CONFIG} is not a directory or does not exist"
        return 1
    fi

    local exclude filter=() file
    for exclude in "${SD_NETWORK_EXCLUDES[@]}"; do
        filter+=("!" "-name" "$exclude")
    done
    for file in $(find "$SD_NETWORK_CONFIG" -depth -type f "${filter[@]}" | sed -e "s|^${SD_NETWORK_CONFIG}/||"); do
        add_file "$SD_NETWORK_CONFIG/$file" "/etc/systemd/network/$file" 444
    done

    add_checked_modules /drivers/net

    # systemd-networkd.service requires user systemd-network
    grep '^systemd-network:' /etc/passwd >>"$BUILDROOT/etc/passwd"
    grep '^systemd-network:' /etc/shadow >>"$BUILDROOT/etc/shadow"
    grep '^systemd-network:' /etc/group >>"$BUILDROOT/etc/group"
}

help() {
    cat <<__EOF_HELP__
This hook allows for initial network setup with systemd initramfs.

It copies all files, binaries and drivers required by systemd-networkd to the
initramfs and enables systemd-networkd.service. Network configuration is copied
from /etc/systemd/network or from \$SD_NETWORK_CONFIG if this variable
specifies an existing directory. With the array SD_NETWORK_EXCLUDES you can
exclude certain configuration files from being copied into initramfs. Specify
globs (e.g. "wg*") or filenames. Always put them in quotes to prevent undesired
behaviour.

SD_NETWORK_CONFIG and SD_NETWORK_EXCLUDES must be set in /etc/mkinitcpio.conf.

See https://github.com/wolegis/mkinitcpio-systemd-extras/wiki/Networking for
details, especially about how to deal with network interface names differing
between initramfs phase and the final operating environment.
__EOF_HELP__
}
