#!/bin/sh

# 	$Id: nsins.sh,v 1.3 2002/08/21 23:20:57 gilles Exp gilles $	

# $Log: nsins.sh,v $
# Revision 1.3  2002/08/21 23:20:57  gilles
# Commented debug mode (set -+x)
#
# Revision 1.2  2002/08/21 04:30:59  gilles
# blanc
#
# Revision 1.1  2002/08/21 04:29:20  gilles
# Initial revision
#


myname=`basename $0`
diff=diff
sed=sed
mktemp=mktemp

# just for the usage
ns_tags=`cat <<EOF
<!-- <navsquare> -->
<!-- </navsquare> -->
EOF
`
# the real work
ns_sed=`cat <<'EOF'
/^<BODY.*>/I{
n
/<!-- <navsquare> -->/!i\\
<!-- <navsquare> -->\\
<!-- </navsquare> -->
}
EOF
`

usage()
{
cat <<EOF
Usage : $myname file1.html [file2.html ...]

The command $myname is a tool to insert navsquare tags 
into HTML files given as arguments, just after the <BODY.*> tag.
The content added to each file will be (if not already there):
$ns_tags
The command will show you the differences between before
and after, for each file. Modification dates are preserved.

EOF

}

doInsert ()
{
	for file in $*; do
		if [ -d $file ]; then 
			echo $file is a directory
			
		elif [ -w $file ]; then
			#set -x
			# unique name
			filetmp=`$mktemp`
			# need to preserve stat
			cp -p  $file $filetmp
			# insert nstag if needed
			$sed -e "$ns_sed" $file > $filetmp
			# 
			echo diff $file $filetmp 
			$diff $file $filetmp 
			# replace
			mv $filetmp $file
			#set +x
		elif [ ! -w $file ]; then
			echo "ERROR: not writable \"$file\""
		else
			echo "ERROR: no file named \"$file\""
		fi
	done
}


is_cmd_here ()
{
    cmd=$1;shift
    args=$*
    if shift; then
	:
    else
	args=--help
    fi
    if ! $cmd $args 1>/dev/null; then
	echo "ERROR: need $cmd command"
        exit 1
    else
	echo $cmd is available
    fi
}



if [ $# = 0 ]; then
	usage
else
	is_cmd_here $diff 
	is_cmd_here $sed
	is_cmd_here $mktemp -p/tmp
	files=$@
	echo will process: $files
	doInsert  $files
fi


