#!/bin/bash

ACTION=$1
VM_IDENT=$2
DEVS=$3

ONAPP_IPTS=/onapp/iptables
VM_IPTS="${ONAPP_IPTS}/${VM_IDENT}"

RULES='nat mangle filter'

restore_rule()
{
    local VM=$1
    local DEV=$2
    local RULE=$3
    local IP6=$4
    local IPTABLES=iptables
    local FILE="${ONAPP_IPTS}/${VM}/${DEV}.${RULE}.ipt"
    if [ -n "$IP6" ]; then IPTABLES=ip6tables; FILE="${FILE}.${IP6}"; fi
    [ ! -f ${FILE} ] && return 0
    ${IPTABLES}-restore -n $FILE
}

delete_rule()
{
    local VM=$1
    local DEV=$2
    local RULE=$3
    local IP6=$4
    local IPTABLES=iptables
    local FILE="${ONAPP_IPTS}/${VM}/${DEV}.${RULE}.ipt"
    if [ -n "$IP6" ]; then IPTABLES=ip6tables; FILE="${FILE}.${IP6}"; fi
    [ ! -f ${FILE} ] && return 0
    IPTABLES="$IPTABLES -t ${RULE}"

    IFS_OLD=$IFS
    IFS=$'\n'
    for CMD in `egrep -i -e "forward|${DEV}" $FILE 2>/dev/null | sed -e 's/-A/-D/g' -e '/^:/d' 2>/dev/null`; do
        RUN="$IPTABLES $CMD"
        echo "$RUN"
        sh -c "$RUN"
    done
    IFS=$IFS_OLD
    unset RUN
}

if [ -z "$DEVS" ]; then
    DEVS=`ls -1 ${VM_IPTS}/ 2>/dev/null | sed 's/\..\+$//g' 2>/dev/null | uniq 2>/dev/null`
fi    

case $ACTION in
    add)
      if [ -f ${VM_IPTS}/.restore_not_needed ]; then
          echo "It seems CP will take care of iptables/ip6tables restore."
          exit 0
      fi
      for DEV in $DEVS; do
          echo "Restore iptables/ip6tables rules for the '$VM_IDENT' and '$DEV'"
          for RULE in $RULES; do
              restore_rule "${VM_IDENT}" "${DEV}" "${RULE}"
              restore_rule "${VM_IDENT}" "${DEV}" "${RULE}" "ip6"
          done
      done
    ;;
    delete)
      for DEV in $DEVS; do
          echo "Delete iptables/ip6tables rules for the '$VM_IDENT' and '$DEV'"
          for RULE in $RULES; do
              delete_rule "${VM_IDENT}" "${DEV}" "${RULE}"
              delete_rule "${VM_IDENT}" "${DEV}" "${RULE}" "ip6"
          done
          iptables -X ${DEV}
          ip6tables -X ${DEV}
      done
    ;;
esac

exit 0
