#!/bin/bash -e
# set ipconfig

. /etc/default/inithooks

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

[[ -e $INITHOOKS_CONF ]] && . $INITHOOKS_CONF
[[ -z "$IP_CONFIG" ]] && exit 0
[[ "$IP_CONFIG" != "manual" ]] \
    && [[ "$IP_CONFIG" != "static" ]] \
    && [[ "$IP_CONFIG" != "dhcp" ]] \
    && fatal "IP_CONFIG set incorrectly"
[[ ! -e /etc/network/interfaces ]] && fatal "intefaces file not found"

APP=$(turnkey-version -n)

IP_IFACE="eth0"
[[ "$APP" == "lxc" ]] && IP_IFACE="br0"

# if IP_CONFIG is not changed skip this script and avoid a interface
# reconfiguration
grep "iface $IP_IFACE inet $IP_CONFIG" /etc/network/interfaces >/dev/null \
    && exit 0

# since debian 8 (systemd) ifdown no longer takes the interface down if we
# change between manual, static or dhcp so using '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

ifup --exclude=lo -a

exit $?
