#!/bin/bash

if [ "${DIB_DEBUG_TRACE:-0}" -gt 0 ]; then
    set -x
fi
set -eu
set -o pipefail

case "$DIB_INIT_SYSTEM" in
    upstart)
        # nothing to do
        exit 0
        ;;
    systemd)
        if [[ ${DISTRO_NAME} =~ (centos|rhel7|fedora) ]]; then
            if [[ ${DIB_SIMPLE_INIT_NETWORKMANAGER} != 1 ]]; then
                # NOTE(pabelanger): Glean requires network.service for
                # these platforms when not using networkmanager
                systemctl enable network.service
            fi
        elif [[ ${DISTRO_NAME} =~ (opensuse) ]]; then
            # on suse, this is named wicked.service, but it's the same
            # as network.service.
            systemctl enable wicked.service
        fi
        ;;
    openrc)
        # let dib-init-system's postinstall handle enabling init scripts
        exit 0
        ;;
    sysv)
        # nothing to do
        exit 0
        ;;
    *)
        echo "Unsupported init system $DIB_INIT_SYSTEM"
        exit 1
        ;;
esac

if [[ ${DIB_SIMPLE_INIT_NETWORKMANAGER} != 0 ]]; then
    # If we are using NetworkManager then we have to avoid having the kernel
    # configure ipv6 addresses on an interface (via router advertisements)
    # until NetworkManager starts. If the interface is configured by the
    # kernel before NetworkManager then NetworkManager will ignore the
    # interface and not configure ipv4 on it. It does this because it assumes
    # some other entity is in control of the interface.
    # Debian has a many year old long bug report detailing this behavior with
    # the most interesting comment being at the end:
    # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=755202#331
    DIB_SIMPLE_INIT_NETWORKMANAGER_IPV6_DELAY=${DIB_SIMPLE_INIT_NETWORKMANAGER_IPV6_DELAY:-30}
    echo "net.ipv6.conf.default.router_solicitation_delay=${DIB_SIMPLE_INIT_NETWORKMANAGER_IPV6_DELAY}" >> /etc/sysctl.conf
fi
