#!/bin/bash

#
# svn_build_prepare.sh: 
#     erzeugen des SPEC und der tar.gz. Ablegen in $DEST/buildsrc/src/PACKETNAME
# überprüfen ob projekt exisitert
# osc commit
# osc build
#
#

[ -z "$BUILD_USES_SVN" ] && BUILD_USES_SVN="yes"

BUILDUSER=$USER
[ -z $DEST_DIR ] && DEST_DIR="/tmp/build.$BUILDUSER"
BUILDTEMP=$DEST_DIR/buildsrc/

if [ ! -r OSC_PACKAGE ]; then
    echo "failed to read config file OSC_PACKAGE"
    exit 1
fi

OSC_PACKAGE=`cat OSC_PACKAGE`

svn_build_prepare.sh $* || {
    echo "failed to prepare sources"
    exit 1
}

# TODO: get this info from svn_build_prepare.sh? seperate script?
if [ -z "$1" ]; then
    # without parameter, we are in source directory
    SPECFILE=$(ls *.spec | awk '{print $1}')
    PACKAGE=$(sed -n -e 's/^Name:\W*//pi' <$SPECFILE)
    # use Version from BUILDSRC, 
    # because it has been modified by svn_build_prepare
    #VERSION=$(sed -n -e 's/^Version:\W*//pi' <$SPECFILE)
    BUILDSRC_DIR=${BUILDTEMP}/src/${PACKAGE}
    VERSION=$(sed -n -e 's/^Version:\W*//pi' <$BUILDSRC_DIR/$SPECFILE)
fi

# RPMs can be handeld directly by osc
# elif [ -r "$1" ]; then
#     # parameter is src.rpm file
#     PACKAGE=`rpm -qp --qf "%{NAME}" $1`
#     VERSION=`rpm -qp --qf "%{VERSION}" $1`

if [ -z "$PACKAGE" ]; then
    echo "nothing to build found!"
    exit 1
fi

echo "Version: $VERSION"

osc co $OSC_PACKAGE || {
    # error message already from osc
    exit 1
}
# rsync is not usable, because ":" is interpretaded as remote host
#rsync -av "$BUILDSRC_DIR/*" "$OSC_PACKAGE/."
#cp -av $BUILDSRC_DIR/* $OSC_PACKAGE/.

cd $OSC_PACKAGE
rsync -a --delete $BUILDSRC_DIR/. . --exclude .osc

# osc build DIST ARCH
#osc add $FILELIST
osc addremove
osc commit -m "release $VERSION"
