#!/bin/bash
iptables -A FORWARD -m mark ! --mark 0 -p tcp --dport 80 -m comment --comment 'OnApp Accelerator' -j ACCEPT # shortcut that assumes no other onapp feature uses iptables/ebtables marking

ebtables -t nat --atomic-file /tmp/ebtables.dat --atomic-init
ebtables -t nat --atomic-file /tmp/ebtables.dat -F

ebtables -t nat --atomic-file /tmp/ebtables.dat -N ACCELERATE
ebtables -t nat --atomic-file /tmp/ebtables.dat -A PREROUTING -p IPv4 --ip-proto tcp --ip-dport 80 --among-dst <all VM MACs> -j ACCELERATE
ebtables -t nat --atomic-file /tmp/ebtables.dat -A ACCELERATE --among-src <all CDNA MACs> -j ACCEPT

arping -f -w 1 -I <bridge name> <CDNA IP>
if [ $? -eq 0 ]; then
  ebtables -t nat --atomic-file /tmp/ebtables.dat -A ACCELERATE --logical-in <bridge name> --among-dst <VM MACs> -j mark --mark-set <10 + bridje ID> --mark-target CONTINUE

  ip rule add fwmark <10 + bridje ID> lookup <10 + bridje ID> # note: check whether the rule already exists, don't add duplicate rules
  ip route add table <10 + bridje ID> default via <CDNA IP> dev <bridge name> onlink # note: check whether the rule already exists, don't add duplicate rules
fi

ebtables -t nat --atomic-file /tmp/ebtables.dat --atomic-commit


sudo ebtables -t nat --atomic-file /tmp/ebtables.dat --atomic-init
sudo ebtables -t nat --atomic-file /tmp/ebtables.dat -F

sudo arping -f -w 1 -I aswj54qzf0vul9 69.168.237.53
if [ $? -eq 0 ]; then
    sudo ebtables -t nat --atomic-file /tmp/ebtables.dat -A PREROUTING -p IPv4 --logical-in aswj54qzf0vul9 --ip-proto tcp --ip-dport 80 --among-dst 00:16:3e:5b:a0:9e --src ! 00:16:3e:4d:0d:b8 -j dnat --to-dst 00:16:3e:4d:0d:b8
fi

sudo ebtables -t nat --atomic-file /tmp/ebtables.dat --atomic-commit

watch '
echo "------------------------------------------";
echo "---------------- EBTABLES ----------------";
echo "------------------------------------------";
ebtables -t nat -L;
echo;\
echo "------------------------------------------";
echo "---------------- IPTABLES ----------------";
echo "------------------------------------------";
iptables -nL;
echo;
echo "------------------------------------------";
echo "---------------- IP  RULE ----------------";
echo "------------------------------------------";
ip rule;\
echo;\
echo "------------------------------------------";
echo "---------------- IP ROUTE ----------------";
echo "------------------------------------------";
ip route list table 11'