#!/bin/sh
#
# This script builds rpms, given an SVN path, RPM basename and SVN revision
# GIT path, GIT revision
# the generated rpms are saved in the 'allrpms' repository, and the names
# are saved in the 'svnrpm' cache.
#
# It prints out the names of the RPMs it generated (to standard output)
# All other info is (should be) printed to stderr
#set -x

# source function library
. /etc/rc.d/init.d/functions

#
# Include al relevent build environment stuff.
#
export PATH=/usr/local/nbe/bin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/home/$MYRELMAN/bin
. /etc/profile.d/nbe.sh

# We need at least one parameters.
if [ $# -eq 0 ]
then
	echo usage: $0 base-rpm-name svn-path svn-revision-number
	exit 1
fi

if [ "$1" = "-d" ]
then
        set -x
        shift
fi

# Verbose option.
VERBOSE=0
if [ "$1" = "-v" ]
then
	VERBOSE=1
	shift
fi

if [ "$1" = "-f" ]
then
        NBE_FORCE="yes"
        shift
fi
if [ "$NBE_FORCE" = "yes" ]
then
        VERBOSE=1
fi

# If one parameter get VCPATH from svn.list.
if [ $# -eq 1 ]
then
	if [ -f $MYSHORTLINK/svn.list ]
	then
		test=`grep ^$1 $MYSHORTLINK/svn.list|awk '{ print $1 }'`
		if [ "$test" = "$1" ]
		then 
			RPMBASE=`grep ^$1 $MYSHORTLINK/svn.list|awk '{ print $1 }'|sed -e "s/\.i386$//" -e "s/\.x86_64//" -e "s/\.i686$//g"`
			VCPATH=`grep ^$1 $MYSHORTLINK/svn.list|awk '{ print $2 }'`
		
			if [ -z "$VCPATH" ]
			then
				echo "SVN path is empty."
				exit 1
			fi	
		else 
			echo "Could nog find svn entry."
			exit 1
		fi	
	fi
fi

# We need at least two parameters to get all parameters from the commandline.
if [ $# -ge 2 ]
then
	# Get the needed info. 
	RPMBASE=`echo $1|sed -e "s/\.i386$//" -e "s/\.x86_64//" -e "s/\.i686$//g"`
	VCPATH=$2
fi

# If this is set, we want to use a specific svn release to build a rpm.
if [ $# -eq 3 ]
then
	if [ -z "`echo $3 | tr -d "[:digit:]"`" -a ! $3="" ]
	then	
		REV=$3
	fi
fi

# dahdi is dependant on CentOS kernels, so always use the latest version.
if [ "$1" = "dahdi-linux" ]
then 
	MYREVISION=
fi    

# Always use the newest repo file
if [ "$1" = "astium-repo" ]
then 
	MYREVISION=
fi    

# Display the rpm we are building.
echo Building $* 1>&2

# Set buildlog.
TMPF=`echo "/tmp/build-$1.log"`

# Set BASEDIR
BASEDIR=~/current/reltree/allrpms/$MYPROD/$MYPRODREL/$MYDIST/$MYARCH/$MYCUST/$MYBUILD/$MYPRODSTABILITY/

#
# Check if we are dealing with subversion, git or a src.rpm.
#
if [ `echo $VCPATH|grep \.src\.rpm$|wc -l` -gt 0 ]
then
	BUILD_TYPE=srpm
elif [ `echo $VCPATH|grep \.git$|wc -l` -gt 0 ]
then
	BUILD_TYPE=git
else
	BUILD_TYPE=svn
fi

#
# Set build arch.
#
if [ `arch` = "i386" -o `arch` = "i686" ]
then
        BUILD_ARCH="i386"
        BASE_ARCH="i386"
fi

if [ `arch` = "x86_64" ]
then
        BUILD_ARCH="x86_64"
        BASE_ARCH="x86_64"
fi

test=`echo $1|grep \.i386$`
if [ -n "$test" ]
then
        BUILD_ARCH="i386"
fi

test=`echo $1|grep \.x86_64$`
if [ -n "$test" ]
then
        BUILD_ARCH="x86_64"
fi

#
# Check if we need to compile a local package or from a remote repository. 
# if VCPATH is not a full URL, assume it is on our repository
#
if [ $BUILD_TYPE = "svn" ]
then

	if [ `echo $VCPATH | grep :// | wc -l` -eq 0 ]
  	then
    		VCPATH=$MYSVNPATH/$VCPATH
        else    
		# Other svn repos have their own numbering.
		# so our numbers should not be used there.	
                MYREVISION=""
                SVN_REVISION=""
  	fi
fi

#
# Check if we need to compile a local package or from a remote repository. 
# if VCPATH is not a full URL, assume it is on our repository
#
if [ $BUILD_TYPE = "git" ]
then
	if [ `echo $VCPATH | grep : | wc -l` -eq 0 ]
  	then
    		VCPATH=$MYGITPATH/$VCPATH
        else    
                MYREVISION=""
                SVN_REVISION=""
  	fi
fi

# Check if we got the srpm, if not, try to get it from the global srpm directory.
if [ $BUILD_TYPE = "srpm" ]
then

	# Set global SRPMS directory.
	GLOBAL_SRPMS="$HOME/current/reltree/allrpms/External-SRPMS/$MYARCH/SRPMS"
	if [ ! -d $GLOBAL_SRPMS ]
	then
		echo "Global SRPMS directory does not exists : $GLOBAL_SRPMS"
    		exit 1
	fi

	# If the SRPMS directory does not exists, create it.
  	if [ ! -d $BASEDIR/SRPMS ]
  	then
		mkdir -p $BASEDIR/SRPMS
  	fi	

  	# If we dont's got the srpm, copy it from the globals srpms directory.
  	if [ ! -f $BASEDIR/SRPMS/$VCPATH ] 
  	then
		if [ -f $GLOBAL_SRPMS/$VCPATH ]
		then
			cp -l "$GLOBAL_SRPMS/$VCPATH" "$BASEDIR/SRPMS" > /dev/null 2>&1
		else 
			echo "Can't find srpm : $VCPATH"
    			exit 1
		fi
  	fi 	
fi

#
# Determine revision number from subversion.
#
if [ $BUILD_TYPE = "svn" ]
then
	# If global myrevision is set and is a digit, use that to build the rpm.
	if [ -z "`echo $MYREVISION | tr -d "[:digit:]"`" -a -n "$MYREVISION" ]
	then
		# Get latest revision.
      		REV=`svn -r $MYREVISION info $VCPATH | grep "^Last Changed Rev:"|sed -e "s/^Last Changed Rev://g"|awk '{ print $1 }'`
	else 	
		# If revision is not set by hand, ask subversion for the revision number.
		if [ -z "$REV"  ]
  		then
			
			# Check if SVN_REVISION is set.
			if [ -z "`echo $SVN_REVISION | tr -d "[:digit:]"`" -a -n "$SVN_REVISION" ]
			then

				# Get latest revision.
      				REV=`svn -r $SVN_REVISION info $VCPATH | grep "^Last Changed Rev:"|sed -e "s/^Last Changed Rev://g"|awk '{ print $1 }'`
  			else 

				# Get latest revision.
      				REV=`svn info $VCPATH | grep "^Last Changed Rev:"|sed -e "s/^Last Changed Rev://g"|awk '{ print $1 }'`
			fi
		fi
	fi

	if [ "$REV" -lt 1  -o -n "`echo $REV | tr -d "[:digit:]"`" ]
  	then
    		echo "Can't determine revision number for $VCPATH"
    		exit 1
  	fi
fi

if [ $BUILD_TYPE = "git" ]
then
	cd
	if [ ! -d gitrepos ]
	then
		mkdir gitrepos
	fi
	cd gitrepos
	if [ ! -d $RPMBASE ]
	then
		git clone -q $VCPATH
	fi
	cd $RPMBASE
	git pull -q
	git fetch --tags -q
	REV=`git rev-parse --short HEAD`
fi

#
# Determine revision number from src.rpm.
#
if [ $BUILD_TYPE = "srpm" ]
then
	REV=`/usr/local/nbe/bin/nbe_srpm_version -s $VCPATH`
fi

# Move cache revision directory to the new place if needed.
if [ -d $BASEDIR/svnrpm/$RPMBASE -a ! -d $BASEDIR/svnrpm/$BASE_ARCH/$RPMBASE ]
then
	mkdir -p $BASEDIR/svnrpm/$BASE_ARCH
	mv $BASEDIR/svnrpm/$RPMBASE $BASEDIR/svnrpm/$BASE_ARCH/$RPMBASE
fi

# Create directories for cache and tmp build.
CACHE=$BASEDIR/svnrpm/$BUILD_ARCH/$RPMBASE
mkdir -p $BASEDIR/RPMS
mkdir -p $BASEDIR/SRPMS
mkdir -p $CACHE

#
# See if the rpms are already generated.
#
if [ -f $CACHE/$REV -a ! "$NBE_FORCE" = "yes" ]
then
	allfound=1
  	for i in `cat $CACHE/$REV`
  	do

    		# Try to find cached version of the rpm.
    		if [ ! -f $BASEDIR/RPMS/$i ]
    		then
      			allfound=0
      			break
    		fi
  	done

  	if [ "$allfound" = "1" ] 
  	then

  		# the sed is a hack, because make does not like ':' in filenames
    		echo " "	
    		cat $CACHE/$REV | sed 's/:/\\:/g'
    		echo $RPMBASE ":UPTODATE" >> $MYBUILDLOG
    		exit 0
  	fi  
fi

# Create the contents of the RPMTOPDIR directory.
/usr/local/nbe/bin/nbe_prep_rpmbuild -d

# Rebuild src.rpm.
if [ $BUILD_TYPE = "srpm" ]
then

	if [ "$VERBOSE" = "1" ]
  	then
    		rpmbuild --target $BUILD_ARCH --rebuild $BASEDIR/SRPMS/$VCPATH 1>&2
    		RETVAL=$?
  	else
    		rpmbuild --target $BUILD_ARCH --rebuild $BASEDIR/SRPMS/$VCPATH > $TMPF 2>&1
    		RETVAL=$?
  	fi
fi

#
# checkout the source, and 'make rpm'
#
if [ $BUILD_TYPE = "svn" ]
then

	# Create builddir if it does not exists yet.
	if [ ! -d $BUILDDIR ]
	then
		mkdir -p $BUILDDIR
	fi

	# Check out the sources.
  	cd $BUILDDIR
  	rm -rf $BUILDDIR/$RPMBASE
  	svn -q co -r $REV ${VCPATH} $RPMBASE
  	cd $BUILDDIR/$RPMBASE

  	# Run the rpm build script.	
  	if [ -x BuildRpm ]
  	then

    		# Create name of lock file.
    		ETH0IP=`/sbin/ifconfig eth0|grep addr:|sed -e s/.*addr:// -e 's/ .*//'`
    		LOCKFILE="/home/$MYRELMAN/locking/nbe_autorebuild.running.$ETH0IP"

    		# Check if we are running within a autorebuild.
    		if [ -f $LOCKFILE ]
    		then

      			# Get autorebuild directory.
      			autorebuild_pid=`cat $LOCKFILE`
      			autobuild_dir=/tmp/nbe_autorebuild.$autorebuild_pid

      			if [ -d $autobuild_dir ]
      			then

        			# Get old revision.
        			OLDREV=`ls $CACHE|sort -n|tail -1`
        			OLDREV=`expr $OLDREV + 1`	

				# If OLDREV is less then 1, reset it to 1.
        			if [ "$OLDREV" -lt 1  ]
        			then
          				OLDREV=1
        			fi

        			# Only get the log for the changes.	
        			svn log ${VCPATH} --revision $OLDREV:$REV > $autobuild_dir/$RPMBASE
      			fi	
    		fi
  	fi

  	if [ "$VERBOSE" = "1" ]
  	then
    		./BuildRpm --target $BUILD_ARCH 1>&2
    		RETVAL=$?
  	else
    		./BuildRpm --target $BUILD_ARCH > $TMPF 2>&1
    		RETVAL=$?
  	fi
fi

if [ $BUILD_TYPE = "git" ]
then

	# Create builddir if it does not exists yet.
	if [ ! -d $BUILDDIR ]
	then
		mkdir -p $BUILDDIR
	fi

	# Check out the sources.
  	cd $BUILDDIR
  	rm -rf $RPMBASE
	git clone -q ${VCPATH}
	cd $RPMBASE
	git checkout -q $REV

  	# Run the rpm build script.	
  	if [ -x BuildRpm ]
  	then

    		# Create name of lock file.
    		ETH0IP=`/sbin/ifconfig eth0|grep addr:|sed -e s/.*addr:// -e 's/ .*//'`
    		LOCKFILE="/home/$MYRELMAN/locking/nbe_autorebuild.running.$ETH0IP"

    		# Check if we are running within a autorebuild.
    		if [ -f $LOCKFILE ]
    		then

      			# Get autorebuild directory.
      			autorebuild_pid=`cat $LOCKFILE`
      			autobuild_dir=/tmp/nbe_autorebuild.$autorebuild_pid

      			if [ -d $autobuild_dir ]
      			then

        			# Get old revision.
        			OLDREV=`ls $CACHE|sort -n|tail -1`
        			OLDREV=`expr $OLDREV + 1`	

				# If OLDREV is less then 1, reset it to 1.
        			if [ "$OLDREV" -lt 1  ]
        			then
          				OLDREV=1
        			fi

        			# Only get the log for the changes.	
        			svn log ${VCPATH} --revision $OLDREV:$REV > $autobuild_dir/$RPMBASE
      			fi	
    		fi
  	fi

  	if [ "$VERBOSE" = "1" ]
  	then
    		./BuildRpm --target $BUILD_ARCH 1>&2
    		RETVAL=$?
  	else
    		./BuildRpm --target $BUILD_ARCH > $TMPF 2>&1
    		RETVAL=$?
  	fi
fi

# Build is succesful.
if [ $RETVAL -eq 0 ] 
then
	# Save exit status to build log.
	echo $RPMBASE ":OK" >> $MYBUILDLOG

	# Remove TMPF buildfile.
	if [ -f $TMPF ]
	then
		rm -f $TMPF
	fi
else
	# Save exit status to build log.
	echo $RPMBASE ":FAILED: See $TMPF for more info !!!" >> $MYBUILDLOG

fi

#
# When build failed, give debug info.
#
if [ $RETVAL -gt 0 ]
then
  	if [ ! "$VERBOSE" = "0" ]
  	then
    		tail -200 $TMPF
    		echo More info may be found in $TMPF
  	fi
  	exit 1
else
	rm -f $TMPF
fi

# Only sign packages if MYSIGNAME is not empty.
if [ -n "$MYSIGNAME" ]
then
	if [ `ls $RPMTOPDIR/RPMS/*/* 2>/dev/null | wc -w` -gt 0 ]
	then
		# Sign the rpms we generated.
		for rpm in $RPMTOPDIR/RPMS/*/* 
  		do 
			echo "$MYSIGSEC" |setsid /bin/rpm --addsign $rpm > /dev/null 2>&1
       		done
	fi
fi

# save the rpms in the rpm allrpms repository
if [ `ls $RPMTOPDIR/RPMS/*/* 2>/dev/null | wc -w` -gt 0 ]
then
	cp -f $RPMTOPDIR/RPMS/*/* $BASEDIR/RPMS
	cd ..
	rm -rf $BUILDDIR/$RPMBASE
fi

# save the names of the rpms in the revision cache
mkdir -p $CACHE
if [ `ls $RPMTOPDIR/RPMS/*/* 2>/dev/null | wc -w` -gt 0 ]
then
	# Add all generated files names to the cache file.	
	for i in $RPMTOPDIR/RPMS/*/* 
  	do 
    		basename $i
  	done > $CACHE/$REV

  	# print the rpms we generated
  	# the sed is a hack, because make does not like ':' in filenames
  	cat $CACHE/$REV | sed 's/:/\\:/g'
else
  	echo nothing generated
fi

