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


UCI_CONFIG="bgp_neighbor"
BIN=quagga
RUN_D=/var/run
ZEBRA_PID_F=$RUN_D/$BIN/zebra.pid
BGP_PID_F=$RUN_D/$BIN/bgpd.pid
conf_f="/etc/quagga/bgpd.conf"
start_bgp_neighbor()
{
	config_get status $1 status
	config_get neighbor_ip $1 neighbor_ip
	config_get as $1 as
	if [ "$status" = "enable" ]; then
	echo "neighbor $neighbor_ip remote-as $as" >> $conf_f
	fi
	
	  
}

stop()
{
	for pid_f in $ZEBRA_PID_F $BGP_PID_F; do
		[ -f "$pid_f" ] && {
			kill $(cat $pid_f)
			rm -f $pid_f
		}
	done
}



start()
{
    
	config_load $UCI_CONFIG
	config_foreach start_bgp_neighbor bgp_neighbor
	uci commit $UCI_CONFIG
	
}

apply()
{		
	stop
	rm -f $conf_f
	echo "hostname v3900" >> $conf_f
	echo "password v3900" >> $conf_f
	as=`uci get quagga.bgp.as` 
	echo "router bgp $as" >> $conf_f
	networks_static=`uci get quagga.bgp.networks_static`
	networks_connected=`uci get quagga.bgp.networks_connected`
	for each_interface in $networks_connected; do
		ip=`json get network.$each_interface.ipaddr`
		mask=`json get network.$each_interface.netmask`
		isup=`json get network.$each_interface.connection`
		if [ "$isup" = "up" -a -n "$ip" -a -n "$mask" ]; then
			eval `ipcalc -p $mask`
			echo "network $ip/$PREFIX" >> $conf_f		
		fi
		
	done 	
	for each_ip in $networks_static; do
		if [ "$each_ip" != "0.0.0.0/0" ] ;then
			echo "network $each_ip" >> $conf_f
		fi
	done 	
	config_load $UCI_CONFIG
	config_foreach start_bgp_neighbor bgp_neighbor
	uci commit $UCI_CONFIG
	[ -f "$ZEBRA_PID_F" ] || zebra -d -u root -g root
	bgpd -d -u root -g root
}

