#!/bin/bash -e

# This script is a wrapper around checkinstall that supports a subset of arch
# linux' PKGBUILD format. This means that it can be used to build debian
# packages from a single file.
#
# PKGBUILD files are written in bash and can define the following variables:
#
# - pkgname [required]
# - pkgver [required]
# - pkgrel [required]
# - pkgdesc
# - arch [required, array] (NOTE: only the first value will be used)
# - url [required]
# - license
# - depends [array]
# - provides [array]
#
# In addition to that, the file *MUST* define the two functions `build` (for
# preparing the files that should be installed) and `package` (for actually
# installing the files).
#
# Both functions have access to a variable `$srcdir` which is the path to a
# temporary directory.

if [ $(id -u) -eq 0 ]; then
	echo "This script should not be run as root!"
	exit 1
fi

join() {
	local IFS=",";
	echo "$*";
}

marker() {
	echo "$(tput setaf 10; tput bold)=== $1 ===$(tput sgr0)"
}

marker 'Setup'
srcdir=$(mktemp -d)
trap "rm -rf $srcdir description-pak; exit" INT TERM EXIT
source PKGBUILD

marker 'Build'
(build)

marker 'Package'
echo "$pkgdesc" > description-pak
checkinstall \
	--default \
	--install=no \
	--nodoc \
	--pkgname="$pkgname" \
	--pkgversion="$pkgver" \
	--pkgrelease="$pkgrel" \
	--pkgarch="$arch" \
	--pkgsource="$url" \
	--pkglicense="$license" \
	--requires="$(join ${depends[@]})" \
	--provides="$(join ${provides[@]})" \
	bash -c "srcdir="$srcdir" && source PKGBUILD && package"