#!/bin/sh /etc/rc.common

UCI_CONFIG="bgp_neighbor"


start_bgp_neighbor()
{
    time=$(date "+%Y-%m-%d %H:%M:%S")
	#config_get status $1 status
	config_get neighbor_ip $1 neighbor_ip
	config_get as $1 as
	config_get status $1 status
	temp_ip=$(cat /tmp/bgp_status | awk -F " " '{print $1}')
	temp_status=$(cat /tmp/bgp_status | awk -F " " '{print $2}')
	#config_get as $1 as
	if [ "$neighbor_ip" = "$temp_ip" -a "$temp_status" = "established" ]; then
		temp_json_status=$(json get bgp_neighbor_status.$1.state -f /var/status_bgp | awk -F "(" '{print $1}')
		if [ "$temp_json_status" != "$temp_status" ]; then
			json -f /var/status_bgp set "bgp_neighbor_status.$1"  \
			ip=$temp_ip as=$as state="$temp_status($time)"
		fi
	fi
	if [ "$neighbor_ip" = "$temp_ip" -a "$temp_status" = "unestablished" ]; then
		temp_json_status=$(json get bgp_neighbor_status.$1.state -f /var/status_bgp | awk -F "(" '{print $1}')
		if [ "$temp_json_status" != "$temp_status" ]; then
			json -f /var/status_bgp set "bgp_neighbor_status.$1"  \
			ip=$temp_ip as=$as state="$temp_status($time)"
		fi
	fi
	
	if [ "$status" = "disable" ]; then
		json delete bgp_neighbor_status.$1 -f /var/status_bgp
	fi
		  
}


start()
{		
  config_load $UCI_CONFIG
  config_foreach start_bgp_neighbor bgp_neighbor
}

