#!/bin/sh
set -e

# FIXME: should have an "undo" option
# FIXME: should use special markers instead of ADDED/DELETED

error()
{
    echo >&2 "ERROR: `basename $0`: $*"
    exit 1
}

PRJONLY=0
if [ "x$1" = "x-p" ]
then
    PRJONLY=1
    shift
fi

usage_error()
{
    echo >&2 "Usage: `basename $0` [-p] oldname newname"
    exit 1
}

[ $# = 2 -a -n "$1" -a -n "$2" ] || usage_error

PRJ=`prcsguess`

# FIXME: should instead adjust $1 and $2 according to position wrt $PRJ
cd `dirname $PRJ`

# move the file unless -p was given
if [ $PRJONLY = 0 ]
then
    [ -r "$1" ] || error "\`$1' does not exist"
    [ ! -r "$2" ] || error "\`$2' already exists"

    mv -v "$1" "$2"
fi

# FIXME: should move the entry and add a comment
# FIXME: should check that newname is not already in used
# FIXME: should barf when src does not exist

# rename in .prj file
NEW=`mktemp $PRJ.XXXXXX`
cat $PRJ | perl -e 'while (<>) { print $_; last if m/^\(Files$/ };
 while (<>) { s|\('$1' |\('$2' |; print $_ };
 while (<>) { print $_ } ' > $NEW
mv $PRJ $PRJ.bak
mv $NEW $PRJ
