#!/bin/sh

# for debugging purpose
set -x

TOPDIRNAME=trunk
SPECDIR=`dirname $0`
echo "SPECDIR=$SPECDIR"

#topdir=`dirname $SPECDIR/../..`
test -z "$SPECDIR" && cd $SPECDIR

if [ -d ".svn" ];then
# within checked-out directory,
# thus need to do svn export
    (which svn) || (echo "faital error. svn not found"; exit)
    if [ "x$EXPORTDIR" = "x" ];then
	EXPORTDIR=`echo "/tmp/$TOPDIRNAME-export"`
    fi

    # create source top level if not exists
    if [ -d "$EXPORTDIR" ]; then
	rm -rf $EXPORTDIR/*
    else
	mkdir -p $EXPORTDIR
    fi
    
    cd ../.. && svn export $TOPDIRNAME $EXPORTDIR/$TOPDIRNAME --force &&
    cd $EXPORTDIR/$TOPDIRNAME/spec-files
fi

if [ x"$TOPDIR" = "x" ]; then
    TOPDIR=`rpm --eval '%_topdir'`;
fi

CMD_RPMBUILD=`which rpmbuild  2>/dev/null`
if [ "x$CMD_RPMBUILD" = "x" ]; then
    CMD_RPMBUILD=`which rpm 2>/dev/null`;
fi

if [ "x$PKG_SOURCE_DIR" = "x" ]; then
    PKG_SOURCE_DIR=`rpm --eval '%_sourcedir'`;
fi
echo $TOPDIR
echo $CMD_RPMBUILD
echo $PKG_SOURCE_DIR

export TOPDIR
export CMD_RPMBUILD
export PKG_SOURCE_DIR

echo $@
exec make "$@"

