#!/bin/sh

. /etc/profile
. /etc/sysconfig/network

set_rules()
{
  #DROP everything in INPUT (Let everything going out)
  iptables -P INPUT DROP
  ip6tables -P INPUT DROP

  #Allow everything on localhost interface
  iptables -A INPUT -i lo -j ACCEPT

  #Allow DHCP protocol on all interfaces
  iptables -A INPUT -p udp --dport 67:68 --sport 67:68 -j ACCEPT
  #Allow ICMP output (ping requests) on all interfaces
  iptables -A INPUT -p icmp -j ACCEPT
  #allow ICMP v6 on all interfaces
  ip6tables -A INPUT -p ipv6-icmp -j ACCEPT

  #allow DNS requests
  iptables -A INPUT -p udp --sport 53 -j ACCEPT
  iptables -A INPUT -p tcp --sport 53 -j ACCEPT

  #allow NTP
  iptables -A INPUT -p udp --dport 123 --sport 123 -j ACCEPT

  # Allow CoAP messages
  # iptables -A INPUT -p udp --dport 5683 -j ACCEPT

  #allow FTP input connections
  # iptables -A INPUT -p tcp --dport 21 -j ACCEPT
  # iptables -A INPUT -p udp --dport 21 -j ACCEPT

  #allow SSH input connections
  iptables -A INPUT -p tcp --dport 22 -j ACCEPT
  iptables -A INPUT -p udp --dport 22 -j ACCEPT

  #allow KMS connections
  # iptables -A INPUT -p tcp --dport 35035 -j ACCEPT

  #allow specific rules
  for file in `find /etc -name "iptables_*.rules"`
  do          
    echo "Applying config file ${file}"
    iptables-restore --noflush < "${file}"
  done     

}

remove_rules()
{
  # Flush Rules
  iptables -F INPUT
  iptables -F OUTPUT
  # Change default Policy
  iptables -P INPUT ACCEPT
  iptables -P OUTPUT ACCEPT
}

# Main script
case "$1" in
  start)
    set_rules
    ;;
  stop)
    remove_rules
    ;;
  restart)
    # Flush Rules
    iptables -F INPUT
    iptables -F OUTPUT
    set_rules
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
    ;;
esac

exit 0
