#!/bin/bash
#-------------------------------------------------------------------------------
# Purpose
#     Build distribution packages for Ubuntu
# Synopsis
#     build_package [options] [revision]
# Options
#     -b  build binary package (instead of source)
# Arguments
#     revision Revision number, optional. If omitted, "1" is used
# Requirements
#     devscripts
#     debhelper
#-------------------------------------------------------------------------------

SETUP_SCRIPT="setup.py"
DIST_ROOT_DIR="dist"
do_binary=0
[[ "$1" == "-b" ]] && do_binary=1 && shift
REVISION=${1:-1}

# Logs a failure message and exits
# Parameters:
#   1 - message
err() {
    echo "ERROR: $1" >&2
    exit 1
}

# Extract name and version values from the setup script file
APP_NAME=$(sed -ne 's/\s*APP_ID\s*=\s*\x27\([^\x27]\+\)\x27.*/\1/p' "$SETUP_SCRIPT")
[[ -n "$APP_NAME" ]] || err "Failed to extract application name"

APP_VERSION=$(sed -ne 's/\s*APP_VERSION\s*=\s*\x27\([^\x27]\+\)\x27.*/\1/p' "$SETUP_SCRIPT")
[[ -n "$APP_VERSION" ]] || err "Failed to extract application version"

echo "Building ${APP_NAME} version ${APP_VERSION} revision ${REVISION}..."

# Verify the changelog contains the appropriate line
[[ "$(dpkg-parsechangelog -S version)" == "$APP_VERSION-$REVISION" ]] ||
    err "The changelog doesn't start with the entry for version $APP_VERSION-$REVISION"

# Initial cleanup: clean the dist dirs
[[ ! -d "$DIST_ROOT_DIR" ]] || rm -rf "$DIST_ROOT_DIR" || err "Removing $DIST_ROOT_DIR failed"

# Run the setup script to create a source tarball
python3 "$SETUP_SCRIPT" sdist || err "Building source tarball failed"

# Add '.orig' and change '-' to '_' before version in tarball's name
TARBALL_NAME="${DIST_ROOT_DIR}/${APP_NAME}_${APP_VERSION}.orig.tar.gz"
mv "${DIST_ROOT_DIR}/${APP_NAME}-${APP_VERSION}.tar.gz" "$TARBALL_NAME" || err "Renaming tarball file failed"

# Unpack the tarball: it will create the release dir
tar --directory "$DIST_ROOT_DIR" -xzf "$TARBALL_NAME" "${APP_NAME}-${APP_VERSION}" || err "Unpacking $TARBALL_NAME failed"

# Copy debian/ into the release dir
RELEASE_DIR="${DIST_ROOT_DIR}/${APP_NAME}-${APP_VERSION}"
cp -r debian "$RELEASE_DIR" || err "Copying debian/ into $RELEASE_DIR failed"

# Build a Debian package
if ((do_binary == 0)); then
    DEBUILD_FLAGS="-S -sa"
else
    DEBUILD_FLAGS="-b"
fi
pushd .
cd "$RELEASE_DIR" || err "Failed to cd $RELEASE_DIR"
debuild $DEBUILD_FLAGS || err "Building Debian package failed"
popd >/dev/null || err "popd failed"

# Cleanup: remove the release dir
rm -rf "$RELEASE_DIR"

# If it was a source package
if ((do_binary == 0)); then
    echo "--------------------------------------------------------------------------------"
    echo "Build succeeded. To upload issue the following command:"
    echo "  dput ppa:yktooo/ppa \"$DIST_ROOT_DIR/${APP_NAME}_${APP_VERSION}-${REVISION}_source.changes\""
    echo "--------------------------------------------------------------------------------"
fi
