File network-autoconfig of Package network-autoconfig

#! /bin/bash
# network-autoconfig: Find a connected eth interface and create an ifcfg for it.
# This script should run at the first boot of a machine
# that has several interfaces
# Author: Martin Vidner <mvidner@suse.cz>
# Reference: https://fate.suse.com/309518 https://fate.suse.com/316111
# Copyright (C) 2010 Novell, Inc.
# Copyright  ©  2014 SUSE LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

# FIXME we assume no config exists. what if it does? display+log a warning and overwrite, or skip
# Be safe when testing, prolly support -h, -v

# Should we check if more cables are connected?
main() {
    # check_dependencies
    for INTERFACE in `interfaces`; do
	if connected $INTERFACE; then
	    create_dhcp_ifcfg $INTERFACE
	    break
	fi
    done
}

# prints non-loopback interface names, one per line
interfaces() {
    ls /sys/class/net | grep -v '^lo$'
}

# $1 is interface name, like eth7
# returns true/false
cable_connected() {
    # ifplugstatus requires ifplugd.rpm
    ifplugstatus $1
    test $? = 2
    # or grep ethtool
}

# $1 is interface name, like eth7
# returns true/false
# requires wicked.rpm
connected() {
    echo >&2 "$0: Trying $1"
    local WBINDIR=/usr/lib/wicked/bin
    $WBINDIR/wickedd-dhcp6 --test $1 | grep ^IPADDR && return 0
    $WBINDIR/wickedd-dhcp4 --test $1 | grep ^IPADDR && return 0
    return 1
}

# $1 is interface name, like eth7
create_dhcp_ifcfg() {
    IFCFG=/etc/sysconfig/network/ifcfg-$1
    if [ -f $IFCFG ]; then
	echo >&2 "$0: ifcfg already exists, will not overwrite $IFCFG"
	return 1
    fi
    echo >&2 "$0: creating $IFCFG"
    cat >$IFCFG  <<EOF
# created by $0
BOOTPROTO='dhcp'
STARTMODE='auto'
EOF
}

main