#!/bin/sh

# this file maintained at http://git.mdcc.cx/uruk.git

# /lib/uruk/init/autodetect-ips - set variables ip{,6}_<interface>_default and
#   net{,6}_<interface>_default

# Copyright © 2012 Wessel Dankers

# This file is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This file is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU GPL for more details.
#
# You should have received a copy of the GNU GPL along with this file, see
# e.g. the file named COPYING.  If not, see <http://www.gnu.org/licenses/>.

# Usage: make sure your /etc/uruk/rc has leading line
# ". /lib/uruk/init/autodetect-ips", e.g. by running
#
#  sed -i '1i. /lib/uruk/init/autodetect-ips' /etc/uruk/rc
#

###############################################
# assign IPs and networks to network interfaces
###############################################

# For each interface <if> in interfaces, ip_<if> should be defined.

# First try Red Hat's init scripts
for f in /etc/sysconfig/network-scripts/ifcfg-*
do
    test -e $f || continue
    i=${f#/etc/sysconfig/network-scripts/ifcfg-}
    case $i in *[!a-zA-Z0-9_]*|[!a-zA-Z_]*)
        continue
    esac
    eval "$(
        . $f
        echo ip_${i}_default=$IPADDR
        echo net_${i}_default=$IPADDR/$NETMASK
        echo ip6_${i}_default=${IPV6ADDR%/*}
        echo net6_${i}_default=$IPV6ADDR
    )"
done

# Second, Debian's init scripts
if test -f /etc/network/interfaces
then
    eval "$(
        while read -r key val val1 rest
        do
            case $key in iface)
                case $val in *[!a-zA-Z0-9_]*|[!a-zA-Z_]*)
                        iface=
                        type=
                ;; *)
                        iface=$val
                        type=$val1
                esac
                address=
                netmask=
            ;; address)
                    address=$val
            ;; netmask)
                    netmask=$val
            esac
            case $iface,$address,$netmask in ?*,?*,?*)
                case $type in inet)
                    echo ip_${iface}_default=$address
                    echo net_${iface}_default=$address/$netmask
                ;; inet6)
                    echo ip6_${iface}_default=$address
                    echo net6_${iface}_default=$address/$netmask
                esac
                iface=
                type=
                address=
                netmask=
            esac
        done </etc/network/interfaces
    )"
fi

