#!/bin/bash
#
# iptsafe
# by loune
# http://siphon9.net/loune/2009/12/iptsafe-iptables-with-dead-mans-switch
# Usage:
# iptsafe -A INPUT -i eth0 -p tcp -s 192.168.0.1 -j ACCEPT
#  or
# iptsafe iptables-save-file
#

iptables-save -c > tmp-iptables-save
if [ ! -z "$2" ]; then
iptables $@
else
iptables-restore < $1
fi

timeout_read() {
  timeout=$1
  varname=$2
  old_tty_settings=`stty -g`
  stty -icanon min 0 time ${timeout}0
  eval read $varname      # or just  read $varname
  stty "$old_tty_settings"
  # See man page for "stty".
}


# Revert to old firewall or not?
echo -n "Do you wish to keep the new rules? [n] "
timeout_read 15 revert

case $revert in
y*|Y*) echo "new rules kept" ;;
*) iptables-restore -c < tmp-iptables-save; echo "iptables restored" ;;
esac

rm tmp-iptables-save
