#!/bin/sh

# enable xtrace output if requested
if [ -n ${ENABLE_XTRACE:-''} ]; then
    set -x
fi

# Build an e2fsprogs RPM from cvs

pwd=`pwd`
currdir=`basename $pwd`
pkgname=`grep Name: e2fsprogs.spec | awk '{print $2;}'`
pkgvers=`grep Version: e2fsprogs.spec | awk '{print $2;}'`
builddir=${pkgname}-${pkgvers}

# ensure that $TMP is set to something
TMP=${TMP:-'/tmp'}

cd ..
tmpdir=`mktemp -d ${RPM_TMPDIR:-$TMP}/rpmtmp.XXXXXX`

# We need to build a tarball for the SRPM using $builddir as the 
# directory name (since that's what RPM will expect it to unpack
# into).  That may require a symlink.

# Make a recursive-symlink copy of the source dir
cp -sR `pwd`/$currdir $tmpdir/$builddir || exit 1

# Remove any build files from the temporary tarball directory
[ -f $tmpdir/$builddir/Makefile ] && make -C $tmpdir/$builddir distclean

EXCLUDE="--exclude .hg* --exclude .pc* --exclude .git* --exclude .git --exclude _topdir"
(cd $tmpdir && tar czfh ${builddir}.tar.gz $EXCLUDE $builddir)

[ "`rpmbuild --version 2> /dev/null`" ] && RPM=rpmbuild || RPM=rpm

# which distro and release
DISTRO=$(lsb_release -is)
RELEASE=$(lsb_release -rs)
# now the hacks in case either is empty
if [ -z "$DISTRO" ]; then
    echo "You really ought to install the lsb_release binary for this distro"
    if grep "Fedora " /etc/issue; then
        DISTRO="Fedora"
    fi
    if grep "SUSE Linux Enterprise Server " /etc/issue; then
        DISTRO="SUSE LINUX"
    fi
fi
if [ -z "$DISTRO" ]; then
    echo "Could not determine the distribution.  Please install the lsb_release binary"
    exit 1
fi
if [ -z "$RELEASE" ]; then
    echo "You really ought to install the lsb_release binary for this distro"
    case "$DISTRO" in
        Fedora)
            RELEASE=$(grep Fedora /etc/issue | sed -e 's/Fedora release //' -e 's/ .*//')
        ;;
        SUSE\ LINUX)
            RELEASE=$(grep SUSE /etc/issue | sed -e 's/SUSE Linux Enterprise Server //' -e 's/ .*//')
        ;;
    esac
fi
if [ -z "$RELEASE" ]; then
    echo "Could not determine the release.  Please install the lsb_release binary"
    exit 1
fi
case "$DISTRO-$RELEASE" in
    RedHatEnterpriseServer-6*) DISTRO=RHEL; RELEASE=6;;
    CentOS-6*) DISTRO=RHEL; RELEASE=6;;
    Fedora-1[234]) DISTRO=RHEL; RELEASE=6;;	# use the same .spec for now
esac

SPECFILE="$currdir/e2fsprogs-${DISTRO// /_}-$RELEASE.spec"
if [ ! -f "$SPECFILE" ]; then
    SPECFILE="$currdir/e2fsprogs.spec"
fi
$RPM --define "_sourcedir $tmpdir" \
     --define "_topdir ${RPM_TOPDIR:-$(rpm -E %_topdir)}" \
     --define "_tmpdir ${RPM_TMPDIR:-$TMP}" \
     --define "extra_config_flags ${EXTRA_CONFIG_FLAGS:-''}" \
     -ba $SPECFILE

rpm_exit=$?
rm -rf $tmpdir
exit $rpm_exit
