#!/bin/sh
#
# add a file to the viwl CVS/RCS repository
#


# check for config
if test -e "/etc/viwl.conf"; then
    # use global config
    . /etc/viwl.conf
fi

if test -e "$HOME/.viwl"; then
    # use personal config
    . $HOME/.viwl
fi

file=$1

if test "x$file" = "x"; then
    echo "usage: $0 <file to checkin>"
fi

if test -d "$file"; then
    echo "argument must be a file!"
    exit
fi


dir=`dirname $file`
file=`basename $file`

#
# check if $dir is absolute or relative, make it absolute
# if it is not
absolute=`echo $dir | grep "^/"`
if test "x$dir" = "x."; then
    dir=""
fi

if test "x$absolute" = "x"; then
    # no, relative
    dir="`pwd`/$dir"
fi


if test "x$VERSION_CONTROL" = "xrcs"; then
    #
    # remove trailing slash
    dir=`echo $dir | sed 's/\/$//'`

    #
    # do all rcs stuff within RCS/
    if test ! -d "$dir/RCS"; then
	mkdir -p $dir/RCS
    fi

    #
    # check if its already being maintained by rcs
    if test -e "${dir}/RCS/${file},v"; then
	echo "$dir/$file is already under RCS maintenance!"
	exit
    else
	#
	# no, it's not
	ci ${dir}/${file}
	co ${dir}/${file}

	#
	# done, report it
	echo "$dir/$file will now maintained via RCS"
    fi
else
    #
    # remove leading slash
    dir=`echo $dir | sed 's/^\///'`

    # add dir to repository, if needed
    CUR_DIR="$WORK_DIR"

    if test ! -d "$WORK_DIR"; then
	echo "CVS working directory $WORK_DIR/ does not exist or is not accessible!"
	exit
    fi
    if test ! -w "$WORK_DIR"; then
	echo "CVS working directory $WORK_DIR/ exists but is not writable!"
	exit
    fi

    perl -e '$_=shift; s/^\///; print join "\n", split /\//; print "\n"' "$dir" | while read subdir; do
	if test ! -d "$CUR_DIR/$subdir"; then
	    # subdir never checked in, do this now
	    mkdir "$CUR_DIR/$subdir" || exit
	    cvs -d $CVS_ROOT add "$CUR_DIR/$subdir" || exit
	fi
	CUR_DIR="$CUR_DIR/$subdir"
    done

    if test -e "$WORK_DIR/$dir/$file"; then
	echo "File $file is already checked in"
	exit
    fi

    #
    # copy our file to the repository
    cp -p "/$dir/$file" "$WORK_DIR/$dir/" || exit

    #
    # check it in
    cvs -d $CVS_ROOT add "$WORK_DIR/$dir/$file" || exit

    #
    # and commit it
    cvs -d $CVS_ROOT commit -m initial "$WORK_DIR/$dir/$file" || exit

    #
    # done, report it
    echo "/$dir/$file will now maintained via CVS"
fi
