#! /bin/bash
set -x
#### Configure variables.  Feel free to change these, but be careful!
SRCDIR=$PWD
# You can pass your own temp directory as an environment variable.
# This prefix is prepended to all directories during "make install" 
FAKEROOT="${SRCDIR}/froot"
# Configure and Compilation directory.
BUILDDIR="${SRCDIR}/build"
# Config variables to mirror those in RPM .spec file
amanda_user=amandabackup
amanda_group=admin
PREFIX="/usr"
EPREFIX="${PREFIX}"
BINDIR="${EPREFIX}/bin"
SBINDIR="${EPREFIX}/sbin"
LIBEXECDIR="${EPREFIX}/lib/amanda"
DATADIR="${PREFIX}/share"
SYSCONFDIR="/etc"
LOCALSTATEDIR="/var"
AMANDAHOMEDIR="${LOCALSTATEDIR}/lib/amanda"
LIBDIR="${EPREFIX}/lib"
INCLUDEDIR="${PREFIX}/include"
INFODIR="${PREFIX}/info"
MANDIR="${DATADIR}/man"
LOGDIR="${LOCALSTATEDIR}/log/amanda"                  

#### CHECKS

if [ ! -f common-src/amanda.h ]
then
    echo "'buildpkg' must be run from the root of an otherwise unused amanda source directory." >&2
    exit 1
fi

if [ ! -f configure ]
then
    echo "The source directory has not been autogen'd -- please download a source distribution tarball or run ./autogen."
    echo "You will need autoconf, automake, and libtool to run autogen (but not to compile from a distribution tarball)."
    exit 1
fi

# Until we get package revisioning in community.
[ -f "PKG_REV" ] || echo "1" > PKG_REV

#### Build functions

do_substitute() {
    # We need to edit packaging/deb/changelog to reflect our current distro
    # and release.  This can't be done within the debian packaging system;
    # dpkg assumes that packages will have the same name on all releases and
    # that apt will prevent users from downloading the wrong build.  We want
    # this information helpfully obvious since we can't rely on apt.
    file_list="packaging/deb/changelog \
        packaging/deb/postinst \
        packaging/deb/postrm \
        packaging/deb/preinst"
    for file in ${file_list}; do
        /usr/bin/perl packaging/common/substitute.pl \
            ${file}.src ${file} || exit 1
    done
}

do_resources() {
    # Setup directories and files as dpkg-buildpkg expects.
    if [ -d debian ]; then
        rm -rf debian
    fi
    cp -Rf packaging/deb debian
    if [ -d $BUILDDIR ]; then
        rm -rf $BUILDDIR
    fi
    mkdir -p $BUILDDIR
    cp -Rfp * $BUILDDIR
}

do_package() {

    echo "Building package"
    cd $BUILDDIR
    # Create unsigned packages
    dpkg-buildpackage -rfakeroot -uc -us
}

do_substitute
do_resources
do_package
