#!/bin/bash

#
# dassbuild_prepare.sh:
#     creates the directory $DEST/buildsrc/src/$NAME
#     and stores there the modified SPEC-file 
#     and the generated tar.gz-archive
#


# environment variables:
#   OSBS_PROJECT (e.g. home:dassit) or config file "OSC_PACKAGE" (e.g. home:dassit/dasscm)

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

if [ -r OSC_LOCAL ]; then
    LOCAL_BUILD="yes"
fi


dassbuild_prepare.sh $*
RT=$?
if [ $RT -eq 1 ]; then
    echo "nothing more to do"
    exit 0
elif [ $RT -gt 1 ]; then
    echo "error: failed to prepare sources"
    exit 1
fi

# 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"

#
# get the openSUSE build service project
#   check for file "OSC_PACKAGE" first,
#   if it is not found, use the variable OSBC_PROJECT
#
if [ -r OSC_PACKAGE ]; then
    OSC_PACKAGE=`cat OSC_PACKAGE`
elif [ "$OSBS_PROJECT" ]; then
    OSC_PACKAGE="$OSBS_PROJECT/$PACKAGE"
else
    OSC_PACKAGE="home:$BUILDUSER/$PACKAGE"
fi

# remove double slashes (/)
OSC_PACKAGE=`sed 's|/[/]*|/|g' <<< $OSC_PACKAGE`

osc co $OSC_PACKAGE || {
    echo
    echo 'An existing "openSUSE Build Service" project must be specified.'
    echo 'To specify it, use the config file OSC_PACKAGE or the environment variable OSBS_PROJECT'
    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 || exit 1
# rsync -a: -rlptgoD
# but we don't want to check for timestamps
# NOTE: this doesn't help, if the data (tar.bz2)
#   contains dynamic data like the Changes file
rsync --checksum -r -v --delete $BUILDSRC_DIR/. . --exclude .osc

if [ "$LOCAL_BUILD" ]; then
    echo 'skipped. Use
# local build:
# osc repos | while read DIST ARCH; do osc build --no-verify $DIST $ARCH; done
# '
else 
    osc addremove
    osc commit -m "release $VERSION"
fi

