#!/bin/sh

estabcount=0
p2count=0
totalcount=0
buferr=0

bounceall() {
/usr/local/etc/rc.d/bgpd.sh stop
sleep 1
$ipsecpath stop
sleep 1
$ipsecpath start
sleep 3
/usr/local/etc/rc.d/bgpd.sh start
}

ipsecpath=/usr/local/sbin/ipsec

echo "=== started at `date` ==="

for con in `$ipsecpath status | grep "\[" | sed 's/\[.*//g' | sort | uniq` ; do 
echo $con
estab=0
p2=0

$ipsecpath status $con | grep ESTAB >/dev/null 2>&1 && estab=1
$ipsecpath status $con | grep INSTALLED >/dev/null 2>&1 && p2=1

[ $estab -eq 1 ] && { 
	echo $con p1 up
	estabcount=$(( $estabcount + 1 ))
	[ $p2 -eq 0 ] && {
	 	echo $con p2 down, restarting
                echo stopping $con...
		$ipsecpath down $con >/dev/null 2>&1
		sleep 1
                echo starting $con...
		$ipsecpath up $con | grep error | grep "buffer space" >/dev/null 2>&1  && { echo "PF_KEY buffer error while starting $con"; buferr=$(( $buferr + 1 )); }
	}

}
[ $estab -eq 0 ] && { echo $con p1 down; }
[ $p2 -eq 1 ] && { echo $con p2 up; p2count=$(( $p2count + 1 )); }
totalcount=$(( $totalcount + 1 ))
done

echo
echo ===
echo estab $estabcount / $totalcount
echo p2 $p2count / $totalcount
echo buf_err $buferr / $totalcount
echo ===
echo

[ $totalcount -gt 0 ] && [ $buferr -gt 0 ] && {
echo $buferr connections show buffer space errors - bouncing openbgpd and ipsec
bounceall
exit
}

[ $totalcount -gt 0 ] && [ $estabcount -eq 0 ] && {
echo no connections have p1 up - bouncing openbgpd and ipsec
bounceall
exit
}

[ $totalcount -gt 0 ] && [ $estabcount -eq $totalcount ] && [ $p2count -eq 0 ] && {
echo all connections have p1 up but no connections have p2 up - bouncing openbgpd and ipsec
bounceall
exit
}

