#!/bin/sh
#set -vx

PROG=`basename $0`

if [ "$#" -lt "3" ]; then
	printf "Usage: $PROG <header> <footer> <file> ...\n"
	printf "Adds a header and footer to all specified files.\n\n"
	printf "Example: $PROG docs/HEADER docs/FOOTER src/common/*.cxx\n\n"
	printf "Report bugs to <sella@digital-genesis.com>.\n"
	exit 1
fi

HEADER=$1
FOOTER=$2
TMPFILE="/tmp/${PROG}.$$"

if [ ! -r "$1" ]; then
	printf "Unable to read HEADER file '$1'.\n\n"
	exit 1
fi

if [ ! -r "$2" ]; then
	printf "Unable to read FOOTER file '$2'.\n\n"
	exit 1
fi

while [ "$#" -ge "3" ]; do
	if [ ! -r "$2" ]; then
		printf "Unable to read input file '$3'. [Skipped]\n\n"
		continue
	fi

	touch $TMPFILE > /dev/null 2>&1 
	if [ $? != 0 ]; then
		printf "Unable to write to temporary file '%s'.\n" $TMPFILE
		exit 1;
	fi

	printf "$3..."

	cat $HEADER > $TMPFILE
	cat $3 >> $TMPFILE
	cat $FOOTER >> $TMPFILE
	mv -f $TMPFILE $3
	if [ $? != 0 ]; then
		printf "Unable to overwrite original file '%s'.\n" $3
		exit 1;
	fi

	printf "done\n"

	shift
done
