#!/bin/bash

CONNTRACK_LIMIT=200000
LOG_PATH='/var/log/zabbix'
FIP_CIDR_1="1.201.136.0/22"
FIP_CIDR_2="1.201.140.0/22"
FIP_PREFIX="1.201."

# Block all FIP
/sbin/iptables -I FORWARD 1 -d $FIP_CIDR_1 -m limit --limit 100/sec -j ACCEPT
/sbin/iptables -I FORWARD 2 -d $FIP_CIDR_2 -m limit --limit 100/sec -j ACCEPT
/sbin/iptables -I FORWARD 3 -d $FIP_CIDR_1 -j DROP
/sbin/iptables -I FORWARD 4 -d $FIP_CIDR_2 -j DROP

# Block to IP (qrouter's Any FIP)
dropped_ip_list=''
for qrouter in `ip netns|grep qrouter`; do
    conntrack=`ip netns exec $qrouter cat /proc/sys/net/netfilter/nf_conntrack_count`
    if [ $conntrack -ge $CONNTRACK_LIMIT ]; then
        for ip in `ip netns exec $qrouter ip a|grep rfp|grep "$FIP_PREFIX"|awk '{print $2}'`; do
            if [ -n "$ip" ]; then
                /sbin/iptables -I FORWARD 1 -d $ip -m limit --limit 100/sec -j ACCEPT
                /sbin/iptables -I FORWARD 2 -d $ip -j DROP
                dropped_ip_list+="${ip} "
            fi
        done
    fi
done

if [ -z "${dropped_ip_list}" ]; then
    dropped_ip_list+="NONE"
    /usr/bin/zabbix_sender -s ${HOSTNAME} -c /etc/zabbix/zabbix_agentd.conf -k conntrack.protect -o "$dropped_ip_list" &>/dev/null
    exit 1
else
# Remove: Block all FIP
    if /sbin/iptables -C FORWARD -d $FIP_CIDR_1 -m limit --limit 100/sec -j ACCEPT &> /dev/null; then
        /sbin/iptables -D FORWARD -d $FIP_CIDR_1 -j DROP
        /sbin/iptables -D FORWARD -d $FIP_CIDR_1 -m limit --limit 100/sec -j ACCEPT
    fi

    if /sbin/iptables -C FORWARD -d $FIP_CIDR_2 -m limit --limit 100/sec -j ACCEPT &> /dev/null; then
       /sbin/iptables -D FORWARD -d $FIP_CIDR_2 -j DROP
       /sbin/iptables -D FORWARD -d $FIP_CIDR_2 -m limit --limit 100/sec -j ACCEPT
    fi
fi

# send the list of dropped ips
/usr/bin/zabbix_sender -s ${HOSTNAME} -c /etc/zabbix/zabbix_agentd.conf -k conntrack.protect -o "$dropped_ip_list" &>/dev/null

# flush conntrack table
/usr/sbin/conntrack -F &> /dev/null
