#!/bin/sh

# Usage:

#  arch-builddaily dir package version
# dir is a directory with your 'dists' tree in it
# package is the name of the package to build
# version is the version number to build

# A new config will be generated for every build, as a record

# There needs to be a config with no version suffix
# (package/upstream/package and package/debian/package) that acquires
# the desired revisions

# For daily builds, use `date +%Y%m%d`-1 as the version, optionally
# with an epoch prefix.

dir="$1"
package="$2"
version="$3"
flavour="$4"

shift 4

set -e

echo "Updating dists tree"
cd "$dir" || exit 1
tla replay || exit 1

if test -z "$version"
then
    echo "No version specified" >&2
    exit 1
fi

if ! test -d "configs/$package"
then
    echo "No package $package found ($dir/configs/$package)" >&2
    exit 1
fi

if test -n "$flavour"
then
    config="$package.$flavour"
    version="$version.$flavour"
else
    config="$package"
fi

if ! test -e "configs/$package/debian/$config"
then
    echo "No suitable configuration present ($dir/configs/$package/debian/$config)" >&2
    exit 1
fi


echo "Going to build $package-$version into $dir/$config/"

if test -e "configs/$package/upstream/$config"
then
    if test -d "$package/upstream/$config"
    then
        echo "Cleaning up old upstream tree"
        rm -rf "$package/upstream/$config"
    fi
    echo "Building $package/upstream/$config"
    tla buildcfg --no-pristines "$package/upstream/$config"
fi

if test -d "$package/$config"
then
    echo "Cleaning up old debian tree"
    rm -rf "$package/$config"
fi

echo "Building $package/debian/$config"
tla buildcfg --no-pristines "$package/debian/$config"

echo "Adding changelog entry"
(cd "$package/$config" && dch -p -v "$version" "Generated by arch-builddaily")

if [ $# -eq 0 ]
then
    echo "arch-buildpackage --skip-upstream-config --skip-debian-config --source-tree=$config $package $version"
    arch-buildpackage --skip-upstream-config --skip-debian-config --source-tree-name=$config "$package" "$version"
else
    echo "arch-buildpackage --skip-upstream-config --skip-debian-config --source-tree=$config $@ $package $version"
    arch-buildpackage --skip-upstream-config --skip-debian-config --source-tree-name=$config "$@" "$package" "$version"
fi
