#! /bin/sh
#
# bu		--- backup a directory
#
# A copy of the backed-up directory is made in $HOME/Backup.
# The correspondence is logged in $HOME/Backup/log.
# The -p flag is used to purge old backups.
#
# AUTHOR: Oscar Nierstrasz (oscar@cui.unige.ch)
# New version 860617
# Revised 910704

B=$HOME/Backup	# all backup directories are symbolic linked to here
log=$B/log	# keep track of back links
pwd=`/bin/pwd`	# current directory to come back to

u="usage: bu [-p(urge)] [<dir> ...]"

# awk script for purging old backups
# field $1 is the name of the backup directory
# field $3 is the name of the backed-up directory
# Scan the log and keep only the last backup of a directory.
# Directories to delete are noted in "rmlog".
purge='/^#/ { next }
{
	flist[NR] = $1		# remember the backup file name
	bulog[$1] = $0		# and the log entry
	busave[$1] = 1		# mark it as new
	if (bu[$3] ~ /./) {
		busave[bu[$3]] = 0	# mark the previous backup as old
		print bu[$3] > "rmlog"	# add it to list of files to rm
	}
	bu[$3] = $1		# remember this one as current backup
}
END {	for (i=1;i<=NR;i++) {
		if (busave[flist[i]])
			printf "%s\n", bulog[flist[i]]
	}
}'

if test ! -d $B
then
	if mkdir $B
	then echo "bu: created directory $B" 1>&2
	else echo "bu: can't mkdir $B" 1>&2 ; exit
	fi
fi

# Get the real pathname:
cd $B
B=`/bin/pwd`

case $# in
0 )	files=$pwd ;;
* )	files=$* ;;
esac

for f in $files
do
	case $f in
	-p )	echo "bu: purging $B" 1>&2
		cd $B
		awk "$purge" log > newlog
		mv newlog log
		if test -s rmlog
		then
			echo -n "bu: deleting" `cat rmlog` "... " 1>&2
			rm -rf `cat rmlog`
			rm rmlog
			echo done 1>&2
		else	echo "bu: nothing to purge" 1>&2
		fi
		continue ;;
	-* )	echo "$u" 1>&2
		exit ;;
	esac

	# $f may be relative to $pwd
	cd $pwd
	dir=`dirname $f`
	cd $dir
	dir=`/bin/pwd`
	file=`basename $f`
	path=$dir/$file
	bu=$file.tar.Z
	num=0

	# Avoid infinite loops
	if test $path = $B
	then
		echo "bu $B: you must be joking!" 1>&2
		continue
	fi

	# Create version number, if necessary
	while test -s $B/$bu
	do
		num=`expr $num + 1`
		bu=$file-$num.tar.Z
	done

	echo Backing up $path 1>&2
	echo in $B/$bu 1>&2

	tar cvf - $file | compress -c > $B/$bu

	echo "# `date`" >> $log
	echo "$bu <-> $path" >> $log
done
exit

