#!/bin/ksh
#
# rmv - CVS RCS file move.
#
#	Usage:	rmv <source> <destination>
#
#	The source and destination must be individual files:
#	You can NOT use this to move multiple files to a directory.
#	You can NOT use this to move a single file to multiple locations.
#		(however you can use this as a first step, then copy
#		 the destination file this produces into the 2nd..nth
#		 location)
#
# XXX directory locking?
#

exitundo ()  (
    rm -f "$DEST";
    rm -f "$DEST.tmp$$":
    mv "$FILE.bak" "$FILE";
    exit 2
)

# Make sure source file exists.
if [ ! -f "$1" ] ; then
    if [ -f "$1,v" ] ; then
	FILE="$1,v"
    else
	echo "Error: $1 does not exist."
	exit 1
    fi
else
    FILE="$1"
fi

if [ -e "`dirname $FILE`/Attic/`basename $FILE`" ] ; then
    echo "Error: $1 is also in the Attic."
    exit 1
fi

if ! cp "$FILE" "$FILE.bak" ; then
    echo "Failed to make backup of $FILE."
    exit 2
fi

# Make sure destination is of the form ...filename,v
if [ "`dirname $2`/`basename $2 ,v`" = "$2" ] ; then
    DEST="$2,v"
else
    DEST="$2"
fi

# Make sure the destination doesn't exist.
if [ -e "$DEST" ] ; then
    echo "Error: The destination $DEST already exists."
    exit 1
fi

if [ -e "`dirname $DEST`/Attic/`basename $DEST`" ] ; then
    echo "Error: $DEST exists in the Attic."
    exit 1
fi

if [ -e "`dirname $DEST`/`basename $DEST ,v`" ] ; then
    echo "Error: checked out destination exists."
    exit 1
fi

if [ -e "$DEST.tmp$$" ] ; then
    echo "Error: temp file for stripsym exists."
    exit 1
fi

# ------------------------
# Procedure:
#	Copy the rcs file.
#	Strip symbolic tags
#	Change all states to dead.
#	Create new (non-dead) revision in new location.
#	cvs rm the previous rcs file.
#

if ! cp "$FILE" "$DEST" ; then
    echo "Error: unable to copy file."
    exitundo
fi

if ! (stripsym < "$DEST" > "$DEST.tmp$$") ; then
    echo "Error: unable to strip symbolic tags."
    exitundo
fi

if ! mv "$DEST.tmp$$" "$DEST" ; then
    echo "Error: unable to strip symbolic tags.(huh:mv?)"
    exitundo
fi

if ! (deadify "$DEST") ; then
    echo "Error: unable to deadify."
    exitundo
fi

# Create a new valid revision.
if ! (cd "`dirname $DEST`" && co -l "`basename $DEST`") ; then
    echo "Error: co of destination failed."
    exitundo
fi

if ! (cd "`dirname $DEST`" &&
      ci -sExp -m"Moved from $FILE" "`basename $DEST`") ; then
    echo "Error: ci of destination failed."
    exitundo
fi

# ----------------------------

# Simulate a "cvs rm"
if ! (cd "`dirname $FILE`" && co -l "`basename $FILE`") ; then
    echo "Error: co of source failed."
    exitundo
fi

if ! (cd "`dirname $FILE`" &&
      ci -sdead -m"Moved to $DEST" "`basename $FILE`") ; then
    echo "Error: ci failed."
    exitundo
fi

if ! mv "$FILE" "`dirname $FILE`/Attic/" ; then
    echo "Error: couldn't throw $FILE in the Attic."
    exitundo
fi

rm -f "$FILE.bak"
exit 0