#!/bin/bash

while true;do
  sleep 10
	ovs_db_status=`ps aux |grep "ovsdb-server " |grep -v grep |wc -l`
	ovs_vswitchd_status=`ps aux |grep ovs-vswitchd |grep -v grep |wc -l`
	ryu_manager_status=`ps aux |grep ryu-manager |grep -v grep |wc -l`
	oext_flow_num=`ovs-ofctl dump-flows ovs-ext |wc -l`
	api_compute_ps=`ps aux |grep api_load |grep -v grep |wc -l`
	api_compute_ss=`ss -ltunp |grep 4433 |grep -v grep |wc -l`

	function add_all_network(){
		while [ `ovs-ofctl dump-flows ovs-ext |wc -l` -eq 1 ];do
			sleep 1
		done
		echo `date +"%Y-%m-%d %T"`" add_all_network!" >> /var/log/network_service.log
		/usr/bin/php /usr/local/zjmf/php/api.php add_all_network
	}

	if [ `ovs-vsctl list-br |grep ovsbr1 |wc -l` -eq 1 -a `brctl show |grep br0 |wc -l` -eq 1 ];then
	  break
	fi

	if [ $ovs_db_status -eq 0 -o $ovs_vswitchd_status -eq 0 -o $ryu_manager_status -eq 0 -o $oext_flow_num -eq 8  -o $oext_flow_num -eq 7 -o -f "/etc/httpd/conf.d/ssl.conf" -o $api_compute_ps -eq 0 -o $api_compute_ss -eq 0 ];then
		if [ $ovs_db_status -eq 0 -o $oext_flow_num -eq 0 ];then
		  echo `date +"%Y-%m-%d %T"`" ovsdb is down!" >> /var/log/network_service.log
			systemctl restart ovsdb-server
		fi

		if [ $ovs_vswitchd_status -eq 0 ];then
		  echo `date +"%Y-%m-%d %T"`" ovs-vswitchd is down!" >> /var/log/network_service.log
			systemctl restart ovs-vswitchd
			add_all_network
		fi

		if [ $ryu_manager_status -eq 0 ];then
		  echo `date +"%Y-%m-%d %T"`" ryu-manager is down!" >> /var/log/network_service.log
			systemctl restart ryu-manager
			add_all_network
		fi

		if [ $oext_flow_num -eq 8 -o $oext_flow_num -eq 7 ];then
		  echo `date +"%Y-%m-%d %T"`" flow table is reseted!" >> /var/log/network_service.log
		  if [ $oext_flow_num -eq 7  ];then
		    ovs-ofctl add-flow ovs-ext "table=0,priority=5,in_port=1,ip6 actions=mod_vlan_vid:100,resubmit(,60)"
		  fi
		  add_all_network
		fi

		if [ -f "/etc/httpd/conf.d/ssl.conf" ];then
		  mv /etc/httpd/conf.d/ssl.conf /tmp
		  systemctl restart httpd
		fi

		if [ $api_compute_ps -eq 0 -o $api_compute_ss -eq 0 ];then
		  echo `date +"%Y-%m-%d %T"`" api_compute is down!" >> /var/log/network_service.log
		  systemctl restart api-compute
		fi
	fi
done