#!/bin/sh

# Usage:

# rmmagic rcsfile
# where "rcsfile" is the path to an RCS ",v" file.  This  file is modified
# in-place.

# This script removes RCS "magic branches".  A magic branch is syntactically
# the same as a version number, but its penultimate branch number is 0.
# "1.2.0.3" is an example.  This mechanism acts as a place-holder for
# branches in the event that no revisions actually exist on the branch.
# For example, "1.2.0.3" identifies version 1.2 if version 1.2.3.1 does not
# exist; otherwise, it identifies the latest revision on the 1.2.3 branch.

# The following procedure is performed:
# - Scan the RCS symbolic name list for magic branches.
# - For each one found:
#   - munge the magic branch into an actual branch number and test for
#     version 1 on that branch.
#   - If no versions exist on the magic branch, check out the version sprouting
#     the branch, and check it back in on the branch.
#   - Move the symbolic name from the magic branch to the actual branch.

# Here is an example:
# - Scanning for magic branches, a magic branch named "foo" is found that
#   points to "1.2.0.3".
# - Check existence of version 1.2.3.1 .
# - If version 1.2.3.1 does not exist:
#   - Check out version 1.2 .
#   - Check in version 1.2.3.1 .
# - Move symbolic name "foo" to point to branch 1.2.3 .

# Note that this script relies on Paul Sander's "rinfo" program in addition
# to RCS and a few standard Unix tools.  The rinfo program can be found at
# <URL: http://www.sander.cupertino.ca.us/ftp/pub/> and at
# <URL: ftp://ftp.sander.cupertino.ca.us/pub>.  It also requires Software
# ChipSet, which is available at the same Web and FTP site.

# This script has been placed in the public domain by its author, Paul
# Sander (paul@sander.cupertino.ca.us).

rcsfile="$1"

t1="/tmp/sh.$$.1"

cleanup() {
	rm -f "$t1"
}
trap cleanup 0 1 2 3 5 15

t() {
	echo "$@"
	eval "$@"
}

comment="Workaround for RCS magic branch"
rcsdir=`dirname "$rcsfile"`
rcsfn=`basename "$rcsfile" ",v"`
rcswf="$rcsdir/$rcsfn"
rinfo -dsummary "$rcsfile" | cut '-d ' -f1 > "$t1"
rinfo +tags < "$rcsfile" |
fgrep '.0.' |
sed -e 's/:/ /' |
(
	read name mbr
	while [ "$name" != "" ]
	do
		bp=`expr "x$mbr" : 'x\(.*\)\.0\.[0-9]*$'`
		bn=`expr "x$mbr" : 'x.*\.0\.\([0-9]*\)$'`
		br="$bp.$bn"
		bv="$br.1"
		if fgrep "$bv" "$t1" > /dev/null
		then
			:
		else
			t co "-r$bp" "$rcsfile" "$rcswf"
			t ci "-f$bv" "'-m$comment'" "$rcsfile" "$rcswf"
		fi
		t rcs "-N${name}:$br" "$rcsfile"
		read name mbr
	done
	true
)

