#!/bin/bash

echo "num of params is $#"
if [ $# -eq 1 ] ; then
	if [ -d $1 ] ; then
		RPMDIR=$1
	else
        	echo "Directory $1 does not exit"
		exit 1	
	fi
else
        RPMDIR="SRPMS"	
fi
cd $RPMDIR
RPMLIST=`echo *src.rpm`
cd ..

if [ ! -e status ]; then mkdir status; fi
if [ ! -e status/complete ]; then mkdir status/complete; fi
if [ ! -e done.$RPMDIR ]; then mkdir done.$RPMDIR; fi

# Run in the background
#if [ -z "$CHILDPROC" ]
#then
#        export CHILDPROC="true"
#        $0 &
#        exit 0
#fi

rm -f status/finished
#rm -f status/buildlog
echo "-----------------------------" >>status/buildlog
echo `date` >>status/buildlog

for RPM in $RPMLIST
do
	if [ -f done.$RPMDIR/$RPM ] ; then
	   echo "Skipping $RPM as it was already done"
           rm $RPMDIR/$RPM
	   continue
	fi  
	echo "Rebuilding $RPM" >> status/buildlog
	NAME=`rpm -qp --qf "%{NAME}" $RPMDIR/$RPM`
	if [ $NAME = "kernel" ] ; then
		RPMOPTS="--target=i386,i686,athlon"
	else
	  if [ $NAME = "glibc" ] ; then
		RPMOPTS="--target=i386,i686"
	  else  	
	    if [ $NAME = "openssl" ] ; then
		RPMOPTS="--target=i386,i686"
	    else  	
		RPMOPTS=""
	    fi
	  fi
	fi
	echo "Rebuilding $RPM with $RPMOPTS" 
	rpmbuild --rebuild $RPMOPTS $RPMDIR/$RPM >status/$RPM.out 2>&1
	grep -q "^Wrote" status/$RPM.out
	if [ $? -eq 0 ]
	then
		mv -f status/$RPM.out status/complete
		mv $RPMDIR/$RPM done.$RPMDIR
		echo "$RPM : success" >> status/buildlog
	else
		echo "$RPM : failed" >> status/buildlog
	fi
done

echo -n "Successfull builds: " >> status/buildlog
grep 'success$' status/buildlog | wc -l >> status/buildlog
echo -n "Failed builds: " >> status/buildlog
grep 'failed$' status/buildlog | wc -l >> status/buildlog

touch status/finished
