#!/bin/bash 
#
# $Id:$
# Copyright (c) 2004 SUSE LINUX AG. All rights reserved.
# Authors: Lars Pinne <lars.pinne@suse.com>
# Desc:    finish a you mirror
#

#
# directory for parameter file. each file must contain all needed values
# for the sync
#
SYNC_PARAM_DIR="/var/lib/YaST2/you/sync"

#
# directory for logfiles
#
SYNC_LOG="/var/lib/YaST2/you/synclog"

#
# destination path for the sync, this is also the install path for the
# client you. so you have to configure exactly this path as a directory
# entry in you httpd.conf
#
DEST_DIR="/var/lib/YaST2/you/mnt"

#
# parse command line
#
case $1 in
	--lastrun|-l)
		if [ ! -f $SYNC_LOG/.youbrush ]
		then	> $SYNC_LOG/.youbrush
			ATIME=""
			MD5FIL="*.rpm"
		else	ATIME="-cnewer $SYNC_LOG/.youbrush"
			MD5FIL=""
		fi
	;;
	--sincesync|-s)
		[ ! -f $SYNC_LOG/.youmirror ] && echo "not found: $SYNC_LOG/.youmirror" 1>&2 && exit 1;
		ATIME="-cnewer $SYNC_LOG/.youmirror"
		MD5FIL=""
	;;
	--all|-a)
		ATIME=""
		MD5FIL="*.rpm"
	;;
	*)
	echo -e "usage: youbrush [OPTION]\n"
	echo "OPTION is one of:"
	echo "	-s	 check packages since last sync of youmirror"
	echo "	-l	 check packages since last run of youbrush"
	echo "	-a	 check all packages"
	exit 1
	;;
esac

#
# simple config check
#
[ ! -d $SYNC_PARAM_DIR ] && logger -t youbrush -s "not found: $SYNC_PARAM_DIR" 1>&2 && exit 1;
[ ! -d $SYNC_LOG ] && logger -t youbrush -s "not found: $SYNC_LOG" 1>&2 && exit 1;
[ ! -d $SYNC_LASTRUN ] && logger -t youbrush -s "not found: $SYNC_LASTRUN" 1>&2 && exit 1;

#
# find newly synced RPMs and remove broken ones 
#
cd $DEST_DIR || (logger -t youbrush -s "not found: $DEST_DIR" 1>&2; exit 1)
TMP1=`mktemp /tmp/youbrush.XXXXXXXXXX` || exit 1
TMP2=`mktemp /tmp/youbrush.XXXXXXXXXX` || exit 1

> $TMP1
> $TMP2
find . -name "*.rpm" $ATIME | while read RPM
do	if MSG=`rpm --checksig $RPM 2>&1`
	then	echo $RPM >> $TMP1
	else	rm -f $RPM
		logger -t youbrush -s $MSG 2>&1 
	fi
	dirname $RPM >> $TMP2 
done

#
# calculate MD5 sums
#
sort -u $TMP2 | while read DIR
do	chmod -R u+w $DIR ||\
		(logger -t youbrush -s "not found: $DIR" 1>&2; exit 1) 
	cd $DIR
	#
	# check if MD5SUMS should be builded from scratch
	#
	[ $(ls *.rpm | wc -l) -le $(wc -l < MD5SUMS) ] && MD5FIL="*.rpm"
	if [ -z "$MD5FIL" -a  -s MD5SUMS ]
	then	cp MD5SUMS MD5SUMS.new
		grep "$DIR" $TMP1 | while read RPM
		do	md5sum `basename $RPM` >> MD5SUMS.new ||\
		  	    logger -t youbrush -s "failed: md5sum $RPM" 1>&2
		done
		sort -k 2 -u -o MD5SUMS.new MD5SUMS.new
	else	md5sum *.rpm > MD5SUMS.new || exit 1
	fi
	
	mv -b MD5SUMS.new MD5SUMS &&\
		logger -t youbrush -s "md5sum $DIR"
	cd $DEST_DIR
	chmod -R a-w $DIR
done

rm -f $TMP1
mv $TMP2 $SYNC_LOG/.youbrush
#
