#!/bin/bash

#Get parameters for ssh and mysql
SSHPORT=$(grep ssh_port /onapp/interface/config/on_app.yml | head -1 | awk {'print $2'} | sed "s/'$//g;s/^'//g;s/\"$//g;s/^\"//g")
MYSQLHOST=$(cat /onapp/interface/config/database.yml | grep host | head -1 | awk '{print $2}' | sed "s/'$//g;s/^'//g;s/\"$//g;s/^\"//g")
MYSQLDB=$(cat /onapp/interface/config/database.yml | grep database: | head -1 | awk '{print $2}' | sed "s/'$//g;s/^'//g;s/\"$//g;s/^\"//g")
MYSQLPW=$(cat /onapp/interface/config/database.yml | grep password | head -1 | awk '{print $2}' | sed "s/'$//g;s/^'//g;s/\"$//g;s/^\"//g")


#For each HV
for hvaddress in `mysql -h $MYSQLHOST $MYSQLDB -uroot -p$MYSQLPW -s -e "select ip_address from hypervisors where online=1;" | grep -v ip_address`; do

        if [ "$hvaddress" = "NULL" ]
        then
                continue #Skip current loop iteration
        fi

        echo "-HV- $hvaddress"  

        #Get iptables rules from HV
        ssh root@$hvaddress -p $SSHPORT "iptables -n -L" > /tmp/iptables-rules.txt

        #For each nic, see if relevant iptables rules exist.
        mysql -h $MYSQLHOST $MYSQLDB -uroot -p$MYSQLPW -s -e "select vms.identifier,nics.identifier from virtual_machines vms left join network_interfaces nics on vms.id=nics.virtual_machine_id where deleted_at is null and booted=1 and hypervisor_id=(select id from hypervisors where ip_address='$hvaddress');" | grep -v identifier | while read vm nic; do
                if [ "$nic" = "NULL" ]
                then
                        echo "VM $vm -- HAS NO NETWORK INTERFACE";
                else
                        if grep -q $nic /tmp/iptables-rules.txt;
                        then
                                echo "VM $vm -- Network interface $nic has iptables rules configured" 
                        else
                                echo "VM $vm -- Network interface $nic DOES NOT HAVE IPTABLES RULES CONFIGURED" 
                        fi
                fi
        done #Close nic loop
        echo ""
done #Close HV loop

rm /tmp/iptables-rules.txt

