#!/bin/bash
# This is a RPM build script that will generate RPMS and SRPMS from a kdevelop source
# dist and a spec file generated by KPP.
# If you have any problems please contact geiseri@yahoo.com

NAME=$1
VERSION=$2
SOURCE=$3
BASE=$4
error ()
{
	echo #### RPM BUILD ERROR ####
        echo There was an error in $RPMERR
	exit 0
}

good ()
{
	echo #### RPMS HAVE BEEN BUILT ####
	exit 1
}

DIR=$BASE/build-$NAME

        sleep 1
        rm -rf $DIR
        echo Starting Build Process
        RPMERR="setting up the build enviroment."
        echo Setting up the build enviroment...
        mkdir -p $DIR/RPMROOT/BUILD/   || error
        mkdir -p $DIR/RPMROOT/RPMS/    || error
        mkdir -p $DIR/RPMROOT/SOURCES/ || error
        mkdir -p $DIR/RPMROOT/SPECS/   || error
        mkdir -p $DIR/RPMROOT/SRPMS/   || error
        mkdir -p $DIR/RPMROOT/tmp/     || error
        mkdir -p $DIR/$NAME-$VERSION   || error
        RPMERR="copying the sources."
        echo Copying the source files...
        cp -a $SOURCE $DIR/RPMROOT/SOURCES                || error
        RPMERR="copying spec file."
        echo Copying the spec files.
        cp -a $BASE/$NAME.spec $DIR/RPMROOT/SPECS         || error
        echo looking for  $BASE/$NAME/lo32-app-$NAME.png
        if [ -f  $BASE/$NAME/lo32-app-$NAME.png ]; then
                RPMERR="converting the RPM icon. Please check to see that $BASE/$NAME/lo32-app-$NAME.png is present"
                echo Converting the RPM icon...
                echo convert $BASE/$NAME/lo32-app-$NAME.png $DIR/RPMROOT/SOURCES/$NAME.xpm
                convert $BASE/$NAME/lo32-app-$NAME.png $DIR/RPMROOT/SOURCES/$NAME.xpm  || error
        else
                echo $BASE/$NAME/lo32-app-$NAME.png was not found, there will not be an application icon included in the R$
        fi
cat > $DIR/rpmmacros <<EOF
%_topdir $DIR/RPMROOT/
%_tmppath $DIR/RPMROOT/tmp/
EOF

cat > $DIR/rpmrc <<EOF
macrofiles: /usr/lib/rpm/macros:/usr/lib/rpm/%{_target}/macros:/etc/rpm/macros:/etc/rpm/%{_target}/macros:~/.rpmmacros:$DIR/rpmmacros
EOF
        RPMERR="building the RPM."
        echo Building the RPM...
        rpm -ba $DIR/RPMROOT/SPECS/$NAME.spec --rcfile $DIR/rpmrc               || error
        RPMERR="copying RPMS"
        echo Copying the RPMS...
        mkdir -p $BASE/upload                                                   || error
        cp -a $DIR/RPMROOT/SOURCES/* $DIR/RPMROOT/SRPMS/* $DIR/RPMROOT/RPMS/*/* $BASE || error
        RPMERR="cleaning up enviroment."
        echo cleaning up enviroment...
        rm -rf $DIR                                                             || error
        echo FINISHED
        good
