#!/bin/sh
#
# Configures cisco a router (given as the last argument) using joe editor
#
# If -n is specified, ignores locking
#

running_limit=20
startup_limit=20
lock=1
if [ "$1" = "-n" ] ; then lock=0 ; shift ; fi
if [ -z "$1" ] ; then echo 'Please supply a router name!' ; exit ; fi

BOX=$1 ; export BOX

. /usr/local/etc/ciscoconf/CiscoConf.conf

cd /usr/local/etc/ciscoconf
HOME=/usr/local/etc/ciscoconf	# to have .joerc read

if [ $lock -eq 0 ] ; then
	escaped_box=`echo $BOX | /usr/bin/sed 's/[.-]/_/g'`
	subst_regex=`eval echo '$subst_regex_'$escaped_box`;
	if [ "$subst_regex" ]
	then
		rcp $BOX:running-config $BOX.tmp \
		&& /usr/bin/perl -p0e "s${subst_regex}s;" < $BOX.tmp >$BOX
		&& /bin/rm $BOX.tmp \
		&& /usr/local/bin/joe $BOX
		rm $BOX
	else
		rcp $BOX:running-config $BOX \
		&& /usr/local/bin/joe $BOX
	fi
else
	lockf -t 0 $BOX.lock $0 -n $BOX
fi

cd /var/db/ciscoconf

i=0
for file in `ls -r $BOX.running*`
do
	if [ $i -lt $running_limit ]
	then
		i=$(( $i + 1 ))
	else
		rm $file;
	fi
done

i=0
for file in `ls -r $BOX.startup*`
do
	if [ $i -lt $startup_limit ]
	then
		i=$(( $i + 1 ))
	else
		rm $file;
	fi
done
