#!/bin/sh
#
# ipmasq-kmod    Set up IP Masquerading kernel modules for Debian systems
#
#                v3.3.0 26 January 1999
#                v3.4.0 4 August 1999

##########
# Options

MODULES=/etc/ipmasq/modules
INSMOD=/sbin/insmod

##########
# Parse commandline options

while [ $# -gt 0 ]; do
    case $1 in
    -v|--verbose)
        SHOWRULES=yes
        ;;
    -n|--no-act)
        NOACT=yes
        ;;
    -d|--display)
        SHOWRULES=yes
        NOACT=yes
        ;;
    -V|--version)
        echo 3.5.10c
        exit 0
        ;;
    -h|--help)
        echo "ipmasq 3.5.10c (c) 1997-2002 Brian Bassett"
        echo "Usage:"
        echo "  ipmasq-kmod            reload IP Masquerade kernel modules" 
        echo "  ipmasq-kmod --verbose  show what modules are being loaded"
        echo "  ipmasq-kmod --no-act   do not actually load any modules"
        echo "  ipmasq-kmod --display  show what modules would be loaded"
        echo "  ipmasq-kmod --version  print version number and exit"
        echo "  ipmasq-kmod --help     show this help message and exit"
        exit 0
        ;;
    esac
    shift
done

##########
# exit if config file is not present
if [ ! -f $MODULES ]; then
    exit 0
fi

##########
# exit if netfilter is the system packetmangler
if [ -e /proc/net/ip_tables_names ]; then
    if [ "$SHOWRULES" = "y" ]; then
	echo "NOTE: ipmasq-kmod does not currently work with the netfilter"
	echo " kernel interface (found on 2.4 kernels)"
	echo "Exiting."
    fi
    exit 0
fi

##########
# functions
load_kmod () {
    # return if called with no parameters
    if [ $# -eq 0 ]; then
        return 0
    fi

    # return if module already loaded
    for i in $LOADED; do
        if [ "$1" = "$i" ]; then
            return 0
        fi
    done

    # compute module string
    buf="ip_masq_$1"
    shift
    if [ $# -gt 0 ]; then
        buf="$buf $@"
    fi
    
    # load the module
    $INSMOD $buf
}

load_all () {
    # get list of all ip_masq_ modules
    MOD_DIR=/lib/modules/$(uname -r)/ipv4/
    MODULES=$(cd $MOD_DIR; ls ip_masq_* | sed -e 's/ip_masq_\(.*\)\.o/\1/g')

    # load them all
    for i in $MODULES ; do
        load_kmod $i
    done

    # quit ipmasq-kmod
    exit 0
}

showanddo () {
    echo $*
    $*
}

##########
# Handle the -d, -n, and -v options

if [ "$SHOWRULES" = "yes" ]; then
    if [ "$NOACT" = "yes" ]; then
        INSMOD="echo $INSMOD"
    else
        INSMOD="showanddo $INSMOD"
    fi
else
    if [ "$NOACT" = "yes" ]; then
        INSMOD="#"
    fi
fi

##########
# Do the modules

LOADED=$(lsmod | cut -f 1 -d ' ' | grep '^ip_masq_' | sed -e 's/^ip_masq_//')
CONFIG=$(cat $MODULES | sed -e 's/#.*$//' -e 's/$/ |/')

buffer=""
for i in $CONFIG; do
    if [ "$i" = "|" ]; then
        if [ "$buffer" = " all" ]; then
            load_all
        else
            load_kmod $buffer
            buffer=""
        fi
    else
        buffer="$buffer $i"
    fi
done

##########
# End of ipmasq-kmod

