#!/bin/sh

CACHE='/etc/eole/iptables'
TCPWRAPPER='/etc/eole/hosts.allow'
TCPWRAPPER_DEST='/etc/hosts.allow'
CACHESET='/etc/eole/ipset'

. /lib/lsb/init-functions

logit() {
    # log dans syslog
    /usr/bin/logger -t "bastion" -p local2.info "$1"
}
logit2(){
    # log dans syslog et sur la console
    FAILURE=$2
    logit "$1"
    log_begin_msg "$1"
    if [ "$FAILURE" = "failed" ]; then
        log_end_msg 1
    fi
}
test_iptables(){
    if [ ! -x /sbin/iptables ];then
        MSG="Erreur : /sbin/iptables non exécutable !"
        logit2 "$MSG" "failed"
        exit 1
    fi
    iptables -nL >/dev/null
    if [ $? -ne 0 ];then
        MSG="Erreur iptables, vérifiez le noyau Linux utilisé par le serveur"
        logit2 "$MSG" "failed"
        exit 1
    fi
}

start() {
    test_iptables
    #echo -n " * Regénération des règles"
    # restore + tcpwrapper
    [ -f $TCPWRAPPER ] && /bin/cp -f $TCPWRAPPER $TCPWRAPPER_DEST
    [ -s $CACHESET ] && ipset restore -exist < $CACHESET
    iptables-restore < $CACHE
    RETVAL=$?
    return $RETVAL
}

stop() {
    logit "Stopping firewall: bastion"
    test_iptables
    /usr/share/eole/firewall.stop
    RETVAL=$?
    log_end_msg $RETVAL
    return $RETVAL
}

case "$1" in
  start)
    start
    ;;

  stop)
    stop
    ;;

  restart|reload)
    stop
    start
  ;;

  status)
    tables=`cat /proc/net/ip_tables_names 2>/dev/null`
    for table in $tables; do
        echo "Table: $table"
        iptables -t $table --list -n
    done
    ;;

  *)
    echo "Usage: $0 {start|stop|restart|reload|status}"
    exit 1
esac

exit 0
