#!/bin/bash

set -e

ACLDIR="/var/cache/xsltdai/arp-acls"
TFTPDIR="/srv/nfs/tftp/acl/Generated"
TFTPPATH="acl/Generated"
CFGDIR="/srv/nfs/tftp/cisco"

if [ "$#" -eq 0 ]; then
	echo "Usage: $0 arp-acl-filename [arp-acl-filename...]" >&2
	exit 1
fi

for acl in "$@" ; do
	echo "=== ACL: $acl"
	diff -uN "$TFTPDIR"/"$acl" "${ACLDIR}"/"$acl" || true
	echo
done | mail -s "DAI-Update: $*" root

rsync -rltO --include '[a-z]*-arp' --exclude '*' --delete "${ACLDIR}"/ "${TFTPDIR}"/

cd "${CFGDIR}"

for acl in "$@" ; do
	DEVICES="$(fgrep -l "ip arp inspection filter $acl " *.cfg | sed 's/\.cfg$//')"
	if [ -z "$DEVICES" ]; then
		echo "Warning: acl '$acl' is not bound on any device. skipping.."
		continue
	fi
	echo "uploading ${acl} to" ${DEVICES} "..."
	ciscoconf -m "${TFTPPATH}"/"$acl" $DEVICES
	ALLDEVICES="$(echo "$ALLDEVICES" ; echo "$DEVICES")"
done

ALLDEVICES="$(echo "$ALLDEVICES" | sort -u)"

if [ -n "$ALLDEVICES" ]; then
	ciscoconf -sc $ALLDEVICES
fi

exit 0
