#!/bin/sh

# *********************************************************************************
# PROJECT NAME   : Iptables  X2 getCounter
# Component name : Iptables firewall counter fetch
# Filename       : iptables_getX2Counter.sh
# Author         : Shivkumar,Wasim Mansuri
# Date created   : 16-10-2018
# ----------------------------------------------------------------------------------
#  Description   :This file is used for grepping and storing the iptables counters.
#                 For every controlled reboot, this file is executed before the
#                 actual reboot to store the counter values currently present.
#                 This value is stored to 2 runtime files X2_COUNTER and TMP_X2.
#                 Once a PM_FETCH has happened, these files are deleted. Again this
#                 gets created once the iptables reboot happens.
#                 This way we do not lose the counter data that gets cleared
#                 through a iptable restart.
# ----------------------------------------------------------------------------------
# Revision history :
# **********************************************************************************
# Copyright (c) Nokia indefinite
# All rights reserved.
# Licensed material - property of Nokia
# **********************************************************************************

X2_IP="/opt/trs/iptables_x2ip"
TMP_X2="/opt/trs/iptables_tmpx2count"
TMP_X2_="/opt/trs/iptables_tmpx2count_"


if [[ -f $X2_IP ]] ; then
    . $X2_IP
    nIp=`wc -l $X2_IP | awk '{print $1}'`
else
    exit 0
fi

# use for loop to read all values and indexes
for (( i=0; i<$nIp; i++ ));
do
    ip1=IP_${i}
    ip=`grep $ip1 $X2_IP | cut -d '=' -f2`
    if [[ $ip =~ .*:.* ]] ;then
        CURRENT_COUNT=`ip6tables -nxvL X2LINK | grep $ip | awk '{print $2}'`
    else
        CURRENT_COUNT=`iptables -nxvL X2LINK | grep $ip | awk '{print $2}'`
    fi
    PREV_COUNT=0
    if [[ -f $TMP_X2 ]]; then
        PREV_COUNT=`grep $ip $TMP_X2 | cut -d '=' -f2`
    fi
    ACTUAL_COUNT=$(($CURRENT_COUNT+$PREV_COUNT+0))
    if [[ "$3" == "PM_FETCH" ]]; then
        echo "${ip}=$ACTUAL_COUNT"
    else
        echo "${ip}=$ACTUAL_COUNT" >>  $TMP_X2_
    fi
done
if [[ -f $TMP_X2_ ]]; then
    mv $TMP_X2_ $TMP_X2
    rm $TMP_X2_
fi
