#!/bin/bash
set -e

srcDir=.

if [ ! -f "$srcDir/debian/changelog" ]; then
    echo "Invalid source directory."
    exit 1
fi

codename=$1
buildDir="$srcDir/.."

if [ -z "$codename" ]; then
    codename="stable"
fi

cut -d" " -f1 "$srcDir/debian/files" |
while read debFile; do
    if [[ ! "$debFile" =~ .*\.deb$ ]]; then
        continue
    fi

    echo "Adding $debFile"
    cp "$buildDir/$debFile" /tmp
    sudo -u www-data reprepro -b /reprepro --gnupghome /reprepro/.gnupg \
        includedeb $codename "/tmp/$debFile"
done

echo "Cleaning."
(cd "$srcDir" && debian/rules clean)
rm -f $buildDir/*.deb
rm -f $buildDir/*.changes
rm -f $buildDir/*.build
rm -f $buildDir/*.buildinfo
