#!/bin/bash -e

# firstboot network interfaces file generation - runs non-interactively.
# - config can be customized via inithooks conf file (i.e. preseed)

# shellcheck source=default/inithooks
source /etc/default/inithooks

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

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

if [[ -z "$IP_CONFIG" ]]; then
    # exit cleanly if env var not set
    exit 0
fi

case "$IP_CONFIG" in
    manual|static|dhcp)
        : # known/valid value, do nothing
        ;;
    *)
        fatal "Invalid: IP_CONFIG='$IP_CONFIG' - valid values: manual|static|dhcp"
        ;;
esac

if ! [[ -e /etc/network/interfaces ]]; then
    fatal "/etc/network/interfaces file not found"
fi


if [[ "$(turnkey-version -n)" == "lxc" ]]; then
    # LXC app not currently being built, but leaving for now...
    IP_IFACE="br0"
else
    IP_IFACE="eth0"
fi

# if IP_CONFIG is not changed avoid a interface redundant reconfiguration
if grep --quiet --no-messages "iface $IP_IFACE inet $IP_CONFIG" \
        /etc/network/interfaces; 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

cat > /etc/network/interfaces <<EOF
# interfaces(5) file - generated by TurnKey firstboot

auto lo
iface lo inet loopback

auto $IP_IFACE
iface $IP_IFACE inet $IP_CONFIG
    hostname $(head -1 /etc/hostname)
EOF

if [[ "$IP_CONFIG" == "static" ]]; then
    cat > /etc/network/interfaces <<EOF
    hostname $(head -1 /etc/hostname)
    address $IP_ADDRESS
    netmask $IP_NETMASK
    gateway $IP_GW
    dns-nameservers $IP_DNS1 $IP_DNS2
EOF
fi

ifup --all --exclude=lo

exit $?
