#!/bin/sh
#
# vi wrapper.
#
# Features locking, file backup
# and version control, if desirable.
#
# requires vim and rcs or cvs.
#
# Copyright (c) 2002  Thomas Linden, <tom@daemon.de>.
#
# $Id$
#


#
# default config, if nothing specified
VERSION_CONTROL="rcs"
FILE_BACKUP="yes"

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

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



for input in "$@"; do
    opt=`printf -- $input | grep "^-"`
    if test "x$opt" != "x"; then
        # option, remove from filelist
        shift
        options="$options $input"
    fi
done

if test "x$@" = "x"; then
    # no input files
    vim $options
    exit
fi



#
# function definitions



function backup {
    file=$1
    if test "x$FILE_BACKUP" = "xyes"; then
	if test ! -e "$file~"; then
	    # make backup copy
	    cp -a "$file" "$file~"
	fi
    fi
}

function checkout {
    file=$1
    if test "x$VERSION_CONTROL" = "xrcs"; then
	# RCS
	if test -e "RCS/$file,v"; then
	    # version controlled file
	    echo "Checking out $input" > /dev/stderr
	    chmod -w "$file"
	    co -l "$file"
	fi
    elif test "x$VERSION_CONTROL" = "xcvs"; then
	# CVS
	# nothing to do
	echo -n "" > /dev/stderr 
    fi
}

function checkin {
    file=$1
    if test "x$VERSION_CONTROL" = "xrcs"; then
	# RCS
	if test -e "RCS/$file,v"; then
	    # version controlled file
	    if test -w "$file"; then
		# need to check it in and out read only
		echo "Checking in $input" > /dev/stderr
		ci "$file"
		co "$file"
	    fi
	fi
    elif test "x$VERSION_CONTROL" = "xcvs"; then
	# CVS
	dir=`dirname $file`
	file=`basename $file`
	if test "x$dir" = "x."; then
	    dir=""
	fi
	dir="`pwd`/$dir"
	dir=`echo $dir | sed 's/^\///'`
	dir=`echo $dir | sed 's/\/$//'`
	repository=`basename $WORK_DIR`
	if test -e "$CVS_ROOT/$repository/$dir/$file,v"; then
	    # version controlled file
	    cp -a "/$dir/$file" "$WORK_DIR/$dir/"
	    cvs -d $CVS_ROOT commit "$WORK_DIR/$dir/$file"
	    cp -a "$WORK_DIR/$dir/$file" "/$dir/"
	fi
    fi
}

# work on every input file
for input in "$@"; do
    if test -e "$input"; then
	# edit file
	dir=`echo $input | sed 's/\/[^\/]*$//'`
	if test -d "$dir"; then
	    # absolute filename
	    cd $dir
	    file=`basename "$input"`
	else
	    file="$input"
	fi

	backup "$file"

	checkout "$file"

	vim $options "$file"

	checkin "$file"

	if test -d "$dir"; then
	    cd -
	fi
    else
	# create file
	vim $options $input
    fi
done

