#!/bin/sh
#
# /sbin/tidy - bonehead version of "neat" - redhat-config-network
#
# Bill Waddington        2004.04.09
#
# 2004.04.10        get rid of code that looked for *wlan* in
#                "up" list, and instead always unload wifi
#                driver if loaded
#
# Provides a very simple network "profile" scheme specific to
# RedHat 9 (2.4.25) on my IBM R40 Centrino laptop.  Invoke with
# a network interface name found in /etc/sysconfig/network-scripts
# as ifcfg-xxxx (use the xxxx) or with "modem" to "down" all active
# interfaces and "up" the requested one.  "modem" will fire up
# kppp and the modem.
#
# /sbin/tidy modem /sbin/tidy eth0 /sbin/tidy wlan0 ...
#
# If the ndiswrapper module is loaded,it will be unloaded
# to quiet the radio.  (and may then get reloaded depending
# on the interface reqested)
#
# Tidy doesn't generate any ifcfg-xxx files, that is up to the user.

ALLDEVLIST=""        # all legit interfaces in /etc/sysconfig/network-scripts
UPDEVLIST=""        # all "up" interfaces per /sbin/ifconfig
DEVFOUND=""        # non-"" if requested interface is legitimate
DEV=""                # utility variable

if [ $UID != 0 ]
then
    echo "$0 requires root privileges"
    su root $0 $1
    exit 0
fi

echo "requested interface is: $1"

if [ "$1" = "" ]
then
    echo "usage: $0 <interface name> | \"modem\""
    exit 1
fi

if [ $1 = "lo" ]
then
    echo "$0 declines to mess with the loopback interface"
    exit 1
fi

ALLDEVLIST=$(ls /etc/sysconfig/network-scripts/ifcfg-* \
        | awk -F"/" '{print $NF}' )

# requested interface must exist in /etc/sysconfig/network-scripts
# or be "modem"

for DEV in $ALLDEVLIST
do
    if [ ${DEV/"ifcfg-"} = $1 ]
    then
        DEVFOUND=$DEV
    fi
done

if [ $1 = "modem" ]
then
   DEVFOUND="modem"
fi

if [ -z $DEVFOUND ]
then
    echo "$0: $1 not found in /etc/sysconfig/network-scripts and isn't \"modem\""
    exit 1
fi

UPDEVLIST=$(/sbin/ifconfig | awk '/^[^\ ]/ {print $1}')

# "down" all the "up"s except loopback

for DEV in $UPDEVLIST
do
    if [ $DEV = "lo" ]
    then
        continue
    fi

    echo "shutting down $DEV"
    /sbin/ifdown $DEV
done

# unload wifi driver if loaded - to quiet the radio

if awk '{print $1}' /proc/modules | grep -q ndiswrapper
then
    echo "unloading ndiswrapper"
    /sbin/rmmod ndiswrapper
fi

#start the requested interface - or dialup via kppp

if [ $1 = "modem" ]
then
    echo "starting kppp"
    /usr/bin/kppp
else
    echo "starting $1"
    /sbin/ifup $1
fi

exit 0