#!/bin/sh

# clear_iptables_rules.sh
# 2022-05-01
# by Gernot Walzl

print_usage () {
  echo "Usage: $0 {ipv4,ipv6} {filter,nat,mangle,raw}"
}

accept_filter () {
  local IPXTABLES="$1"
  if [ "$IPXTABLES" != "iptables" -a "$IPXTABLES" != "ip6tables" ]; then
    return 1
  fi
  $IPXTABLES -P INPUT ACCEPT
  $IPXTABLES -P FORWARD ACCEPT
  $IPXTABLES -P OUTPUT ACCEPT
  $IPXTABLES -F
  $IPXTABLES -X
}

accept_nat () {
  local IPXTABLES="$1"
  if [ "$IPXTABLES" != "iptables" ]; then
    return 1
  fi
  $IPXTABLES -t nat -P PREROUTING ACCEPT
  $IPXTABLES -t nat -P POSTROUTING ACCEPT
  $IPXTABLES -t nat -P OUTPUT ACCEPT
  $IPXTABLES -t nat -F
  $IPXTABLES -t nat -X
}

accept_mangle () {
  local IPXTABLES="$1"
  if [ "$IPXTABLES" != "iptables" -a "$IPXTABLES" != "ip6tables" ]; then
    return 1
  fi
  $IPXTABLES -t mangle -P PREROUTING ACCEPT
  $IPXTABLES -t mangle -P INPUT ACCEPT
  $IPXTABLES -t mangle -P FORWARD ACCEPT
  $IPXTABLES -t mangle -P OUTPUT ACCEPT
  $IPXTABLES -t mangle -P POSTROUTING ACCEPT
  $IPXTABLES -t mangle -F
  $IPXTABLES -t mangle -X
}

accept_raw () {
  local IPXTABLES="$1"
  if [ "$IPXTABLES" != "iptables" -a "$IPXTABLES" != "ip6tables" ]; then
    return 1
  fi
  $IPXTABLES -t raw -P PREROUTING ACCEPT
  $IPXTABLES -t raw -P OUTPUT ACCEPT
  $IPXTABLES -t raw -F
  $IPXTABLES -t raw -X
}

case "$1" in
 'ipv4')
  case "$2" in
   'filter')
    accept_filter iptables
    ;;
   'nat')
    accept_nat iptables
    ;;
   'mangle')
    accept_mangle iptables
    ;;
   'raw')
    accept_raw iptables
    ;;
   *)
    print_usage
    ;;
  esac
  ;;
 'ipv6')
  case "$2" in
   'filter')
    accept_filter ip6tables
    ;;
   'mangle')
    accept_mangle ip6tables
    ;;
   'raw')
    accept_raw ip6tables
    ;;
   *)
    print_usage
    ;;
  esac
  ;;
 *)
  print_usage
  ;;
esac