#!/bin/bash
distribution=hardy
svnuri="$(invirt-getconf svn.uri)"

set -e
if  [ $# -eq 0 ] ; then
	echo " usage: invirt-build-release package_name [package_name [...]]"
	exit 1
fi

for package; do
    rm -rf build-release/$package
    svn export $svnuri/trunk/packages/$package build-release/$package
    cd build-release/$package
    
    eval $(perl -ne 'print if s/^(Version|Source|Distribution): /\1=/' \
             <(dpkg-parsechangelog))
    dpkg-buildpackage -us -uc -rfakeroot -S
    cd ..
    arch_any=0
    sed -ne 's/^Architecture: //p' ${Source}_${Version}.dsc | while read arch; do
        case "$arch" in
            all)
                ;;
            any)
                arch_any=1;;
            *)
                echo "invirt-build-release: arch '$Architecture' unimplemented" >&2
                exit 1;;
        esac
    done
    if [ $arch_any -eq 0 ]; then
        sbuild -d $distribution --arch-all   ${Source}_${Version}.dsc
    else
        sbuild -d $distribution --arch amd64 --arch-all ${Source}_${Version}.dsc
        sbuild -d $distribution --arch i386  ${Source}_${Version}.dsc
    fi

    if ! svn ls $svnuri/package_tags/$Source >/dev/null 2>&1; then
        svn mkdir $svnuri/package_tags/$Source \
            -m "Create package tags directory"
    fi
    if ! svn ls $svnuri/package_tags/$Source/$Version >/dev/null 2>&1; then
        svn cp $svnuri/trunk/packages/$package $svnuri/package_tags/$Source/$Version \
            -m "Tag $Version of $Source"
    else
        echo "$(basename $0): tag already exists, not making again"
    fi
    
    [ $Distribution = 'unstable' ] \
        || echo "$(basename $0): warning: Distribution is $Distribution, script expects unstable"
    changesfile=`pwd`/${Source}_*${Version}*.changes
    for i in $changesfile; do
        reprepro-env include unstable $i
        reprepro-env copy stable unstable $(sed -ne 's/^Binary: //p' $i)
    done
    reprepro-env copy stable unstable $Source
    
    cd ..
    rm -rf build-release/$package
done
