#!/bin/bash
set -o pipefail

# compat for removed initscripts dependency

success() {
       echo "[  OK  ]"
       return 0
}

failure() {
       echo "[FAILED]"
       return 1
}

# internal variables
EBTABLES_CONFIG=/etc/sysconfig/ebtables-config
EBTABLES_DATA=/etc/sysconfig/ebtables
EBTABLES_TABLES="filter nat"
if ebtables --version | grep -q '(legacy)'; then
    EBTABLES_TABLES+=" broute"
fi
VAR_SUBSYS_EBTABLES=/var/lock/subsys/ebtables

# ebtables-config defaults
EBTABLES_SAVE_ON_STOP="no"
EBTABLES_SAVE_ON_RESTART="no"
EBTABLES_SAVE_COUNTER="no"

# load config if existing
[ -f "$EBTABLES_CONFIG" ] && . "$EBTABLES_CONFIG"

initialize() {
    local ret=0
    local table=''
    for table in $EBTABLES_TABLES; do
        ebtables -v -t $table --init-table || ret=1
    done
    return $ret
}

sanitize_dump() {
    local drop=false
    local line=''

    export EBTABLES_TABLES

    while read -r line;
    do
        case $line in
        \**)
            drop=false
            local table="${line#\*}"
            local found=false
            local t=''
            for t in $EBTABLES_TABLES; do
                if [[ $t == $table ]]; then
                    found=true
                    break
                fi
            done
            $found || drop=true
            ;;
        esac
        $drop || echo "$line"
    done < $1
}

start() {
    if [ -f $EBTABLES_DATA ]; then
        echo -n "ebtables: loading ruleset from $EBTABLES_DATA: "
        sanitize_dump $EBTABLES_DATA | ebtables-restore
    else
        echo -n "ebtables: no stored ruleset, initializing empty tables: "
        initialize
    fi
    local ret=$?
    touch $VAR_SUBSYS_EBTABLES
    return $ret
}

save() {
    echo -n "ebtables: saving active ruleset to $EBTABLES_DATA: "
    export EBTABLES_SAVE_COUNTER
    ebtables-save >$EBTABLES_DATA && success || failure
}

case $1 in
    start)
        [ -f "$VAR_SUBSYS_EBTABLES" ] && exit 0
        start && success || failure
        RETVAL=$?
        ;;
    stop)
        [ "x$EBTABLES_SAVE_ON_STOP" = "xyes" ] && save
        echo -n "ebtables: stopping firewall: "
        initialize && success || failure
        RETVAL=$?
        rm -f $VAR_SUBSYS_EBTABLES
        ;;
    save)
        save
        RETVAL=$?
        ;;
    *)
        echo "usage: ${0##*/} {start|stop|save}" >&2
        RETVAL=2
        ;;
esac

exit $RETVAL
