#!/bin/bash -e
#
# obs-update-tarball.sh - Update Buildservice Sources
#

NAME="foo"
VERSION="1.0"

# CVSROOT
CVSROOT=":ext:me@myscvsserver/cvsroot"

# CVS tag
CVSTAG=

# CVS module (directory under cvsroot)
MODULE="foo"

# Name of first directory in tarball. If empty $NAME-$VERSION will be used
TARDIRNAME=

# If your build system can generate it's own tarballs, set the command here.
# eg: "python setup.py sdist" or "make tarball"
PKGCMD=

# If PKGCMD is used and it does not generate a file of the form
# $NAME-$VERSION.tar.bz2, set what it should be here
PKGFILE=


# Make sure CVS_RSH is set
export CVS_RSH=/usr/bin/ssh

# Exit status. 0 if no changes, 1 if error occurred, 2 if changes occurred
STATUS=0

if [ ! -f .osc/_package ] ; then
    echo "This is not a buildservice package directory"
    exit 1
fi

# Generate package, if upstream code is newer
#
echo "Checking if we need to update $NAME"

if [ -z "$CVSTAG" ] ; then
    CVSTAG='HEAD'
fi

if [ ! -z "$VERSION" ] ; then
    namever="$NAME-$VERSION"
else
    namever="$NAME"
fi

if [ -z "$TARDIRNAME" ] ; then
    TARDIRNAME="$namever"
fi

if [ -z "$PKGFILE" ] ; then
    PKGFILE="$namever.tar.bz2"
else
    PKGFILE="$TARDIRNAME/$PKGFILE"
fi

pkgfilename=`basename $PKGFILE`

doupdate="false"

# Update package from buildservice
osc up

if [ ! -f $pkgfilename ] ; then
    # Tarball does not exist, needs to be created
    doupdate="true"
    # This may be a new version, so remove any older versions if they exist
    oldtarballs=`ls -1 | grep -P "^$NAME[-\.\d]*tar.bz2$" ||:`
    if [ ! -z $oldtarballs ] ; then
        rm $oldtarballs
    fi
else
    # Check date on tarball and see if any checkins were made since it was
    # created
    last_update=`stat --format='%y' $pkgfilename`
    output=`cvs -d $CVSROOT rdiff -s -r $CVSTAG -D "$last_update" $MODULE 2> /dev/null`
    if [ ! -z "$output" ] ; then
        doupdate="true"
    fi
fi

if [ $doupdate = "false" ] ; then
    # Nothing to update
    exit 0
fi

# Set status to signal caller that changes occurred
STATUS=2

echo "Building $NAME source package"
# Build new tarball
tmpdir=`mktemp -d`
trap "rm -rf $tmpdir" ERR INT TERM
pushd $tmpdir > /dev/null
cvs -d $CVSROOT checkout -d $TARDIRNAME -r $CVSTAG $MODULE

if [ ! -z "$PKGCMD" ] ; then
    cd $TARDIRNAME
    $PKGCMD
    cd ..
else
    tar --exclude=CVS -cjf $PKGFILE $TARDIRNAME
fi
popd > /dev/null
mv -f $tmpdir/$PKGFILE .
rm -rf $tmpdir

# If this is the primary tarball, named the same as the spec file, update
# the version if required
for spec in *.spec ; do
    if grep -q "^# use_pkginfo_version $NAME" $spec ; then
        echo "Updating version in $spec"
        sed "s/^Version:.*/Version:       $VERSION/" $spec > $spec.new
        mv $spec.new $spec
    fi
done

# Check it in
osc addremove
osc ci -m "Automatic update by obs-update-tarball.sh"

exit $STATUS

