#!/bin/sh
# DocumentId:	$Id: dpsyco-skel,v 1.8 2001/09/13 15:31:17 ola Exp $
# Author:	$Author: ola $
# Date:		$Date: 2001/09/13 15:31:17 $
# Summary:
#	Handle the syncronization of the skels.
# Arguments:	$1	Source.
#		$2	Destination.
#    (optional)	$3	Rsync options.
#

SOURCE="$1"
DESTR="$2"
RSYNCOPT="$3"

if [ ! -d "$SOURCE" ] ; then
    echo "Source $SOURCE is not a directory, exiting."
    exit 0
fi

if [ ! -d "$DESTR" ] ; then
    echo "Destination $DEST is not a directory, exiting."
    exit 0
fi
DESTAPP=$(echo "$DESTR" | sed -e "s|^/||;")
DEST=$(echo "$DESTR" | sed -e "s|/$||;")

CDIR=$(echo "/var/lib/dpsyco-skel/$DESTAPP" | sed -e "s|/$||;")
mkdir -p $CDIR
OLDLISTF=$CDIR/skel.list
LISTF=$CDIR/tmpskel.list
BDIR=$CDIR/skel

touch $OLDLISTF

find $SOURCE -depth | sed -e "s|^$SOURCE||;" | sed -e "s|^/||;" | grep -v "^$" | sort > $LISTF

SEPREM="< "
SEPADD="> "
# Compare the two skeleton files and see what files that have been removed.
diff $OLDLISTF $LISTF | grep "$SEPREM" | sed -e "s|^$SEPREM||;" | {
    while read FILE ; do
	if [ -e "$DEST/$FILE" -a ! -d "$DEST/$FILE" -a ! -L "$DEST/$FILE" ] ; then
	    # Should it be restored or should it be deleted?
	    if [ -e "$BDIR/$FILE" ] ; then
		echo "Restore $DEST/$FILE from backup."
		mv "$BDIR/$FILE" "$DEST/$FILE"
	    else
		if [ -e "$DEST/$FILE" ] ; then
		    echo "Searching for $DEST/$FILE in the installed packages."
		    if dpkg -S "$DEST/$FILE" > /dev/null 2>&1 ; then
			echo "$DEST/$FILE found, not removed. Nothing to restore from though."
		    else
			echo "Remove $DEST/$FILE. Removed from dpsyco skel and nothing to restore."
			rm -f "$DEST/$FILE"
		    fi
		else
		    echo "File $DEST/$FILE removed from skel and but was already deleted."
		fi
	    fi
	elif [ -d "$DEST/$FILE" ] ; then
	    if rmdir "$DEST/$FILE" > /dev/null 2>&1 ; then
		echo "Directory $DEST/$FILE successfully removed."
	    fi
	fi
    done
}
# Compare the two skeleton files and see what directories that have been
# removed.
diff $OLDLISTF $LISTF | grep "$SEPREM" | sed -e "s|^$SEPREM||;" | {
    while read FILE ; do
	if [ -d "$DEST/$FILE" ] ; then
	    if rmdir "$DEST/$FILE" > /dev/null 2>&1 ; then
		echo "Directory $DEST/$FILE successfully removed."
	    fi
	fi
    done
}
# Compare the two skeleton files and see what files that have been added.
diff $OLDLISTF $LISTF | grep "$SEPADD" | sed -e "s|^$SEPADD||;" | {
    while read FILE ; do
	if [ -e "$DEST/$FILE" -a ! -d "$DEST/$FILE" -a ! -L "$DEST/$FILE" ] ; then
	    # Does the file exist in the backup dir?
	    if [ ! -e "$BDIR/$FILE" ] ; then
		if [ -e "$DEST/$FILE" ] ; then
		    echo "Backing up $DEST/$FILE."
		    TMPC=$(echo "$BDIR/$FILE" | sed -e "s|/[^/]*$||;")
		    mkdir -p $TMPC
		    rsync -a "$DEST/$FILE" "$BDIR/$FILE"
		else
		    echo "Creating $DEST/$FILE from skel."
		fi
	    fi
	fi
    done
}

# Sync in a new version.
rsync -rltD -I $RSYNCOPT "$SOURCE/" "$DESTR"

# Store the new skel as the old one.
mv $LISTF $OLDLISTF
