#!/bin/bash

# Do a test Debian package build. Will exit with 0 on success, non-zero for any
# failure.

set -e

VERBOSE=1

BASE_TMP_DIR=/var/tmp

#### ###### ###### ###### ###### ###### ###### ##
progress () {
    local CURDT
    if [ "$VERBOSE" == "1" ]; then
        CURDT=$(date --iso-8601=sec)
        echo "progress[$CURDT]: $1"
    fi
}
#### ###### ###### ###### ###### ###### ###### ##

# 1. Create a temporary directory to do the build in.
BUILD_DIR=$(mktemp -d -p ${BASE_TMP_DIR} -u debuild-XXXX)
progress "BUILD_DIR is $BUILD_DIR"

# 2. Clone the package repository
mkdir -p "$BUILD_DIR"
cd "$BUILD_DIR"
progress "build directory prepared"

git clone https://code.stanford.edu/debian-public/test-package-build.git
cd test-package-build
progress "repository cloned"

# 3. Build Debian package. As we are running this anonomously, we want
#    the package files to be unsigned. We also turn off apt package caching.
export GIT_PBUILDER_OPTIONS='--aptcache ""'
gbp buildpackage --git-pbuilder > /dev/null
progress "package built"

# 4. Verify that the the .deb file was created and contains the correct
#    file(s).
progress "package contents validation starting..."
dpkg --contents ../test-package-build*.deb > ../package-contents.txt
grep '/etc/hello.txt' ../package-contents.txt > /dev/null
progress "...package contents validated"

# 5. Clean up.
cd "${BASE_TMP_DIR}"
rm -rf "${BUILD_DIR}"
progress "build directory removed"

progress "test build passed; exiting"
exit 0


DOCS=<<__END_OF_DOCS__

=for stopwords
Adam Lewenberg

=head1 NAME

test-build - Do a test Debian package build

=head1 SYNOPSIS

test-build

=head1 DESCRIPTION

B<test-build> clones a Debian native package from code.stanford.edu and
does a Debian package build validating that the build was successful.  It
is intended as a way to verify that the server on which the script is run
supports Debian package builds. In particular, it is well-suited to be
used as an application-levvel monitor.

=head1 RETURNS

0 on success, non-zero otherwise.

=head1 SEE ALSO

pbuild(1)

=head1 AUTHORS

Adam H. Lewenberg <adamhl@stanford.edu>

=cut

