#!/bin/bash
echo ""

if [ "$4" == "a" ];
then
	ACTION=a
elif [ "$4" == "d" ];
then
	ACTION=d
else
	echo "$./change_vpn_peer.sh <hostname> <oldpeer> <newpeer> <action>"
	echo ""
	echo "  hostname is firewall name as used in observium"
	echo ""
	echo "  oldpeer|newpeer are IP addresses of remote gateway"
	echo ""
	echo "  action can be a or d"
	echo "    a applies configuration to firewall"
	echo "    d just displays configuration"
	echo ""
	exit
fi

ASA=$1
OLDPEER=$2
NEWPEER=$3
CONF=/home/rancid/var/rancid/network/configs/$ASA
CONFIG=/scripts/rancid/changepeer_$ASA_$OLDPEER_$NEWPEER.txt

echo "UPDATE Konfigfile via rancid to have the latest config file"
/home/rancid/bin/rancid-run  -r asa-hosting
echo ""

echo "CHECK for old peer IP in config file"
grep "tunnel-group $OLDPEER" $CONF || ( echo "tunnel group not found" && exit ) > /dev/null 2>&1
echo "Old peer found"
echo ""

echo "GET crypto map name for old peer IP"
CMNAME=`grep "crypto map" $CONF | grep "set peer $OLDPEER" | awk '{print $3}'` > /dev/null 2>&1
echo " ~ $CMNAME"
echo ""

echo "GET crypto map entry for old peer IP"
CMENTRY=`grep "crypto map" $CONF | grep "set peer $OLDPEER" | awk '{print $4}'` > /dev/null 2>&1
echo " ~ $CMENTRY"
echo ""

echo "GET old PSK"
PSK=`egrep -A2 "tunnel-group $OLDPEER ipsec-att" $CONF | grep pre` > /dev/null 2>&1
echo " ~ $PSK"
echo ""

echo "GET old GroupPolicy"
GROUP=`egrep -A1 "tunnel-group $OLDPEER general-att" $CONF | grep default-group-policy` > /dev/null 2>&1
echo " ~ $GROUP"
echo ""

echo "WRITE configuration file"
echo "
config t

!Remove old tunnel-group
no tunnel-group $OLDPEER ipsec-attributes

!Re-Configure new tunnel-group
tunnel-group $NEWPEER type ipsec-l2l
tunnel-group $NEWPEER ipsec-attributes
$PSK
exit
tunnel-group $NEWPEER general-attributes
$GROUP
exit

!Remove Old Peer from Crypto map
no crypto map $CMNAME $CMENTRY set peer $OLDPEER

!Create New Peer on Crypto Map
crypto map $CMNAME $CMENTRY set peer $NEWPEER

clear config tunnel-group $OLDPEER

!Save Config
end
wr mem
" > $CONFIG
echo ""

if [ "$ACTION" == "a" ];
then
	echo "APPLY configuration file"
	/home/rancid/bin/clogin -x $CONFIG $ASA
elif [ "$ACTION" == "d" ];
then
	echo "DISPLAY configuration file"
	echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
	cat $CONFIG
	echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
fi

echo ""
echo " ~~~ THE END ~~~"
echo ""

