#!/bin/sh
#
#  Guralp Systems Ltd.
#
#  Check for possibly out of date .local files in /etc.
#
#  Copyright (c) 2010 R.J.Dunlop    <rdunlop@guralp.com>
#  Released under the GNU GPLv3. See file COPYING or
#  http://www.gnu.org/copyleft/gpl.html for details.
#

TDIR=/etc
TLOCAL=".local"
TTPL=".tpl"

RETVAL=0
SHOWDIFF=True
COPYOVER=""

usage() {
	echo "Check local configuration against factory templates."
	echo
	echo "usage: $(basename $0) [option]"
	echo
	echo "Options:"
	echo "    --help        Show this message."
	echo "    --list-only   Only list the file names (do not show diffs)."
	echo "    --copy-over   DANGEROUS.  Copy templates to .local files."
}


# Check args (only one at a time allowed)
if [ $# -gt 1 ]
then
	usage
	exit 1
fi
case "X$1" in
X)		;;
X--help)	usage ; exit 0			;;
X--list-only)	SHOWDIFF=""			;;
X--copy-over)	COPYOVER="True"	SHOWDIFF=""	;;
*)		usage ; exit 1			;;
esac


# Cat a files contents stripped of comments and blank lines
stripcomments() {
        local file="$1"

	sed -e 's/#.*//' -e '/^[   ]*$/d' $file
}


# Check a template file and .local for equality after stripping comments
check_files() {
	local tname=$1
	local lname=$2

	local t1=$(mktemp -t)
	local t2=$(mktemp -t)

	stripcomments $tname > $t1
	stripcomments $lname > $t2

	if diff -b $t1 $t2 > /dev/null 2>&1
	then
	    : Files are the same
	else
	    echo "Files $tname and $lname differ"
	    if [ -n "$SHOWDIFF" ]
	    then
		diff -a -u $lname $tname
	    fi
	    if [ -n "$COPYOVER" ]
	    then
		echo "Copying $tname to $lname"
		cp -i $tname $lname < /dev/tty
	    else
		RETVAL=1
	    fi
	fi

	rm -f $t1 $t2
}


# Find the template files and check each in turn
cd /
find $TDIR -name "*$TTPL" | sort | while read tname
do
	lname="$(dirname $tname)/$(basename $tname ${TTPL})${TLOCAL}"

	if [ -r $tname -a -r $lname ]
	then
	    check_files $tname $lname
	fi
done

exit $RETVAL
