#!/bin/sh
# Use RCS if available
RCSCI=/usr/bin/ci
RCSRLOG=/usr/bin/rlog
RCSCO=/usr/bin/co
RCSOPT=
DIFFOPT=-c
while true
do
	if [ "$1" = "--rcsopt" ] ; then
		RCSOPT=$2
		shift
		shift
	elif [ "$1" = "--diffopt" ] ; then
		DIFFOPT=$2
		shift
		shift
	else
		break
	fi
done
if [ $# != 3 ] ; then
	echo cfgarchive [ --rcsopt options ] --arch path_file family
	echo "   " add a new copy of this file to the archive
	echo "   " it expects it from its standard input
	echo cfgarchive [ --rcsopt options ] --extr path_file family
	echo "   " extract the latest version of the file
	echo "   " and send it on its standard output
	echo cfgarchive [ --rcsopt options ] --hist path_file family
	echo "   " sends on its standard output the revision history
	echo "   " It outputs one line per revisions
	echo "   " The format is important as it is parsed by linuxconf
	echo cfgarchive [ --rcsopt options ] --diff path_file family
	echo "   " sends on its standard output the difference between
	echo "   " the current config file and the last one archived
else
	FILE=$2
	FAMILY=$3
	TARGET=/etc/linuxconf/archive/$FAMILY$FILE
	DIR=`dirname $TARGET`
	if [ "$1" = "--arch" ] ; then
		mkdir -p $DIR
		chmod 700 /etc/linuxconf/archive
		cat >$TARGET
		# Only archive if RCS is there
		if [ -x $RCSCI ] ; then
			if [ ! -f $TARGET,v ] ; then
				$RCSCI $RCSOPT $TARGET <<-EOF
				.
				EOF
				rcs -U $TARGET
			else
				ci $RCSOPT $TARGET <<-EOF
				.
				EOF
			fi
			rm -f $TARGET
		fi
	elif [ "$1" = "--extr" ] ; then
		if [ -f $TARGET,v ] ; then
			$RCSCO $RCSOPT $TARGET 2>/dev/null
			cat $TARGET
			rm -f $TARGET
		elif [ -f $TARGET ] ; then
			cat $TARGET
		else
			# This tells linuxconf that the file was never
			# archived so it is better to leave the current copy in place
			echo "### no arch ###"
		fi
	elif [ "$1" = "--hist" ] ; then
		cat >/dev/null
		if [ -x $RCSRLOG ] ; then
			if [ -f $TARGET,v ] ; then
				IFS=" ;"
				$RCSRLOG $RCSOPT $TARGET | while read verb arg1 arg2 rest
				do
					case $verb in
					revision)
						rev=$arg1
						;;
					date:)
						echo $rev $arg1 $arg2
						;;
					esac
				done
			else
				echo $TARGET was never archived
			fi
		else
			if [ -f $TARGET ] ; then
				ls -l $TARGET
			else
				echo $TARGET was never archived
			fi
		fi
	elif [ "$1" = "--diff" ] ; then
		mkdir -p $DIR
		chmod 700 /etc/linuxconf/archive
		cat >$TARGET.cur
		# Only archive if RCS is there
		if [ -x $RCSCO ] ; then
			if [ -f $TARGET,v ] ; then
				$RCSCO $RCSOPT $TARGET 2>/dev/null
				diff $DIFFOPT -N $TARGET $TARGET.cur
				rm -f $TARGET
			else
				diff $DIFFOPT -N $TARGET $TARGET.cur
			fi
		else
			diff $DIFFOPT -N $TARGET $TARGET.cur
		fi
		rm -f $TARGET.cur
	else
		echo cfgarchive: Invalid argument >&2
	fi
fi

