#!/bin/sh
#
# Usage: rules [binary|clean]
#

if [ ! -f VERSION -o ! -f Makefile ]; then
	echo "This command must be run from the main source directory!" >&2
	exit 1
fi

RC=~/.rpmmacros
RPMS="BUILD RPMS SOURCES SPECS SRPMS tmp"
DIR=`pwd`/tmp
NAME=cntlm-`cat VERSION`

function restorerc {
	if [ -f $RC.tmp$$ ]; then
		rm -f $RC				# In case it didn't exist before
		mv $RC.tmp$$ $RC 2>/dev/null		# mv wouldn't overwrite it, there'd be no source
	fi
}

trap restorerc INT					# Make sure we don't destroy original rc file

if [ "$1" = "binary" ]; then
	make clean
	rm -f cntlm*.rpm 2>/dev/null
	cp $RC $RC.tmp$$ 2>/dev/null			# Save originam rpm configuration
	cat >> $RC << _EOF_
%_builddir      %{_topdir}/BUILD
%_rpmdir        %{_topdir}/RPMS
%_sourcedir     %{_topdir}/SOURCES
%_specdir       %{_topdir}/SPECS
%_srcrpmdir     %{_topdir}/SRPMS
%_topdir        $DIR
_EOF_

	for i in $RPMS; do mkdir -p $DIR/$i; done	# Create new rpm build structure
	TMP=`pwd`
	rm -f $DIR/tmp/$NAME 2>/dev/null
	ln -s $TMP $DIR/tmp/$NAME			# Generate source .tar.gz
	sed "s/^\./$NAME/" doc/files.txt | tar zchf $DIR/SOURCES/$NAME.tar.gz --no-recursion -C $DIR/tmp -T -
	cp redhat/cntlm.* $DIR/SOURCES/			# Prepare build environment

	rpmbuild -ba $DIR/SOURCES/cntlm.spec		# Build RPM and copy to current dir
	cp $DIR/SRPMS/*rpm . 2>/dev/null
	cp $DIR/RPMS/*/cntlm*rpm . 2>/dev/null

	restorerc
elif [ "$1" = "clean" ]; then
	for i in $RPMS; do rm -rf $DIR/$i; done		# Clean the whole mess, keep packages
	rmdir $DIR 2>/dev/null || true
fi
