#!/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`



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)
    VERSION=$(sed -n -e 's/^Version:\W*//pi' <$SPECFILE)
elif [ -r "$1" ]; then
    # parameter is src.rpm file
        PACKAGE=`rpm -qp --qf "%{NAME}" $1`
        VERSION=`rpm -qp --qf "%{VERSION}" $1`
fi


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

BUILDSRC_DIR=${BUILDTEMP}/src/${PACKAGE}


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

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/.

if [ "$BUILD_USES_SVN" = "yes" ]; then
    echo "receiving subversion information ..."
    # set RELEASE number (last modification in this directory)
    # requires subversion (but connection to server isn't neccessary)
    SVN_BUILD_RELEASE=$(unset LANG; svn info . | sed -n 's/^Last Changed Rev: \([0-9]*\)/\1/p')
    # in case of local modification a "m" is added to the release number
    SVN_BUILD_MODIFIED=$(svn status -v | grep "^ *M" | wc -l)
    # checks if a file is commited, 
    # but update on its directory is not performed
    SVN_LAST_MODIFICATION=$(svn status -v | sed -n 's/^ *[0-9]* *\([0-9]*\) .*/\1/p' | sort -n | tail -1)
    if [ $SVN_BUILD_MODIFIED -gt 0 ]; then  
        SVN_BUILD_RELEASE=${SVN_BUILD_RELEASE}m
    elif [ $SVN_LAST_MODIFICATION -ne $SVN_BUILD_RELEASE ]; then
        SVN_BUILD_RELEASE=${SVN_BUILD_RELEASE}p
    fi
    echo "SVN_BUILD_RELEASE: $SVN_BUILD_RELEASE"
fi

cd $OSC_PACKAGE
pwd
#echo "OSC_PACKAGE"
# osc build DIST ARCH
osc add *
if [ "$SVN_BUILD_RELEASE" ]; then
    osc commit -m "release $SVN_BUILD_RELEASE"
fi