#!/bin/sh

# FileTraq v0.2
# Copyright (c) 2000 Jeremy Weatherford
# See COPYING file included with distribution

# v0.1: first release
# v0.2: incorporates changes suggested by Chris Ausbrooks

# designed to be run periodically from any root's crontab, with output going in mail to root

# Defaults file

defaults=/etc/default/filetraq

# scans /etc/filetraq.conf unless given a different list

file=/etc/filetraq.conf

# uses /var/lib/filetraq for backups unless given a different dir

backupdir=/var/lib/filetraq

# diff options
diffopts="-p1"
# diff order
difforder="newold"

# Source defaults file if available
test -f $defaults && source $defaults

if [ "$1" != "" ]; then
	if [ "$1" = "--help" ]; then
		echo "FileTraq version 0.2"
		echo "Syntax: $0 [filelist] [backupdir]";
		echo "Defaults can be set in '/etc/default/filetraq'."
		echo "If no filelist is specified, default is $file."
		echo "If no backupdir is specified, default is $backupdir."
		exit
	fi
	if [ ! -r $1 ]; then
		echo "Filelist $1 does not exist or cannot be read."
		exit
	fi
	file=$1
fi

if [ "$2" != "" ]; then
	if [ ! -d $2 ]; then
		echo "Backupdir $2 is not a directory."
		exit
	fi
	backupdir=$2
fi

# Exit quietly if there's no config file
test -r $file || exit 0

for entry in `cat $file | cut -d "#" -f 1`; do
    for name in `find $entry -xtype f 2>&1`; do
	if [ "$name" = "find:" ]; then
	    echo "File not found, or pattern didn't match any files: $entry"
	    break
	else
	    backup=$backupdir/`echo $name \
		| sed -e 's/^\/\(.*\)$/\1/' -e 's|/|\.|g'`
	    if [ ! -e $backup ]; then
		echo "Creating first backup of $name."
		cp -af $name $backup
	    else
		if [ "$difforder" = "oldnew" ]; then
		  diff $diffopts $backup $name
		else
		  diff $diffopts $name $backup
		fi
		
		if [ $? = 1 ]; then
		    # changes to save
		    cp -af $backup $backup.`date +%m.%d.%y__%H.%M`
		    cp -af $name $backup
		fi
	    fi
	fi
    done
    if [ "$ret" = "1" ]; then
	echo "File not found: $entry"
    fi
done
