#!/bin/sh
# Build a zzz rpm set. 
# Uses temp space here, does not touch the source.
# Runnable as myself, does not use root permission at all.

PROG="`basename $0`"

usage () {
	cat <<EOF
Usage: $PROG SPECFILE SOURCE [SOURCE ...]

Builds the RPM package(s) driven by SPECFILE from
the given SOURCEs, using the temporary build area specified 
by the ``%_topdir`` declaration in ``~/.rpmmacros``.

If SOURCE is a file, copy it to the RPM temporary build area.
If SOURCE is a directory, then make a .tar.gz file out of it,
and copy the .tar.gz to the build area.
EOF
}

die () {
	rc="$1"
	shift

	echo -n "$PROG: "
	if [ -z "$1" ]; then cat 1>&2; else echo 1>&2 "$@"; fi
	
	exit $rc
}


## process cmd line args

spec="$1";
echo SPEC_FILE=$spec

# rest  of args is SOURCE files...'
source="$2";
echo SOURCES=$source

topdir="$3";
echo BUILDING_DIR=$topdir

utiljar="$4";
echo UTIL_JAR=$utiljar

# some Java parameters
if [ -z "$JAVA_HOME" ]; then
  echo "Error: JAVA_HOME is not set."
  echo " .. try to continue .. " 
else
  echo "run java in $JAVA_HOME"
  JAVA_HOME=$JAVA_HOME
fi

JAVA=/usr/java/latest/bin/java
echo JAVA=$JAVA

PLATFORM=`${JAVA} -cp ${utiljar} -Xmx32m it.grid.storm.Platform platform | sed -e "s/ /_/g"`
echo NATIVE_PLATFORM=$PLATFORM

OS_DIST=`${JAVA} -cp ${utiljar} -Xmx32m it.grid.storm.Platform os_dist | sed -e "s/ /_/g"`
echo OS_DIST=$OS_DIST

# make rpm directory structure
echo "make rpm directory structure ", $topdir
if [ ! -d "$topdir" ]; then
        echo 'oo ', $topdir
	mkdir -v $topdir
fi

echo "create rpm directory structure ", $topdir
mkdir -p -v $topdir/SOURCES
mkdir -p -v $topdir/SRPMS
mkdir -p -v $topdir/SPECS
mkdir -p -v $topdir/BUILD
mkdir -p -v $topdir/RPMS

echo "rm the source(s)"
rm -rf $topdir/SOURCES/$source

echo "copy the source(s) ", $source
cp -v $source $topdir/SOURCES/

echo "now build the binaries and the rpms. ", $spec
cp -v $spec $topdir/SPECS/

cd $topdir

echo "create rpm $topdir"
# Generate RPMs
#rpmbuild --define "_topdir ${topdir}" --define "platform ${PLATFORM}"  -ba SPECS/storm-backend-server.spec
rpmbuild --define "_topdir ${topdir}" --nodeps -ba SPECS/storm-backend-server.spec

