#!/bin/bash -e

# firstboot network interfaces file generation - runs non-interactively.
# - config can be customized via inithooks conf file (i.e. preseed)
# - decisions and file rendering live in lib/ipconfig.sh

INITHOOKS_DEFAULT="${INITHOOKS_DEFAULT:-/etc/default/inithooks}"
INTERFACES="${INTERFACES:-/etc/network/interfaces}"

# shellcheck source=default/inithooks
source "$INITHOOKS_DEFAULT"
# shellcheck source=lib/ipconfig.sh
source "$INITHOOKS_PATH/lib/ipconfig.sh"

fatal() { echo "fatal $*" >&2; exit 1; }

if [[ -e $INITHOOKS_CONF ]]; then
    source $INITHOOKS_CONF
fi

if [[ -z "$IP_CONFIG" && -z "$IP6_CONFIG" ]]; then
    # exit cleanly if neither env var is set
    exit 0
fi

# with only the IP6_* keys set, IPv4 stays as the image ships it
IP_CONFIG=${IP_CONFIG:-dhcp}

ipconfig_valid_config "$IP_CONFIG" \
    || fatal "Invalid: IP_CONFIG='$IP_CONFIG' - valid values: manual|static|dhcp"

[[ -z "$IP6_CONFIG" ]] || ipconfig_valid_config "$IP6_CONFIG" \
    || fatal "Invalid: IP6_CONFIG='$IP6_CONFIG' - valid values: manual|static|dhcp"

if [[ "$IP6_CONFIG" == "static" ]]; then
    error=$(ipconfig_check_static6 "$IP6_ADDRESS" "$IP6_GW" "$IP6_DNS1" "$IP6_DNS2") \
        || fatal "$error"
fi

if ! [[ -e $INTERFACES ]]; then
    fatal "$INTERFACES file not found"
fi

IP_IFACE=$(ipconfig_iface "$(turnkey-version -n)")

# if the config is not changed avoid a interface redundant reconfiguration
if ipconfig_unchanged "$INTERFACES" "$IP_IFACE" "$IP_CONFIG" "$IP6_CONFIG"; then
    exit 0
fi

# under systemd, ifdown no longer takes the interface down when changing
# between manual, static or dhcp so use 'ip' instead
ip link set $IP_IFACE down

HOST_NAME=$(head -1 /etc/hostname)

ipconfig_render_head "$IP_IFACE" "$IP_CONFIG" "$HOST_NAME" > "$INTERFACES"

if [[ "$IP_CONFIG" == "static" ]]; then
    error=$(ipconfig_check_static "$IP_ADDRESS" "$IP_NETMASK") || fatal "$error"
    ipconfig_render_static "$IP_ADDRESS" "$IP_NETMASK" "$IP_GW" "$IP_DNS1" "$IP_DNS2" \
        >> "$INTERFACES"
fi

ipconfig_render_inet6 "$IP_IFACE" "$HOST_NAME" "$IP6_CONFIG" >> "$INTERFACES"

if [[ "$IP6_CONFIG" == "static" ]]; then
    ipconfig_render_static6 "$IP6_ADDRESS" "$IP6_GW" "$IP6_DNS1" "$IP6_DNS2" \
        >> "$INTERFACES"
fi

ifup --all --exclude=lo

exit $?
