#!/bin/bash

# This script will scan for sub-directories in /logs which have
# a name that is a decimal dotted IP address. These directories
# will then be exported via NFS to that IP address to provide
# a centralised location for logfiles.

function explog() {
	IFS=" "
	if [ $# -ne 4 ]; then return; fi
	if [ -z "$1" -o $1 -lt 1 -o $1 -gt 254 ]; then return; fi
	if [ -z "$2" -o $2 -gt 254 ]; then return; fi
	if [ -z "$3" -o $3 -gt 254 ]; then return; fi
	if [ -z "$4" -o $4 -lt 1 -o $4 -gt 254 ]; then return; fi
	
	# Looks like an IP address
	ip="$1.$2.$3.$4"
	
	# If there is not already an entry for this unit in /etc/exports, then add one
	grep -q "^/logs/$ip" /etc/exports
	
	if [ $? -ne 0 ]; then
		echo "/logs/$ip $ip(no_subtree_check,insecure,anonuid=0,anongid=0,rw,all_squash)" >> /etc/exports
	fi
}

for x in /logs/[0-9]*.[0-9]*.[0-9]*.[0-9]*; do
	if [ -d "$x" ]; then
		f=`basename $x`
		IFS="./"
		explog $f
	fi
done

# Now remove any exports for which the corresponding directory no long exists
for x in `grep "^/logs/" /etc/exports`; do
	if [ ${x:0:6} = "/logs/" ]; then
		if [ ! -d $x ]; then
			cp /etc/exports /etc/exports.bak
			grep -v "^$x" /etc/exports.bak > /etc/exports
		fi
	fi
done

# If this script is run without arguments, then it is assumed that a log directory has
# just been added and it will be exported now ...
if [ -z "$1" ]; then
	exportfs -r
fi

