#*******************************************************************************
#**  This file is part of Pecunia.                                           ***
#**                                                                          ***
#**  Copyright (C) 2017, 2018, 2019, 2020, 2021, 2023                        ***
#**  John Schneiderman <Licencing _AT_ Schneiderman _DOT_ me>                ***
#**                                                                          ***
#**  This program is free software: you can redistribute it and/or modify it ***
#**  under the terms of the GNU Lesser General Public License as published   ***
#**  by the Free Software Foundation, either version 3 of the License, or    ***
#**  (at your option) any later version.                                     ***
#**                                                                          ***
#**  This program is distributed in the hope that it will be useful, but     ***
#**  WITHOUT ANY WARRANTY; without even the implied warranty of              ***
#**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                    ***
#**  See the GNU Lesser General Public License for more details.             ***
#**                                                                          ***
#**  You should have received a copy of the GNU Lesser General Public License***
#**  along with this program. If not, see <http://www.gnu.org/licenses/>.    ***
#*******************************************************************************

#!/usr/bin/env bash
shopt -s -o nounset
shopt -s -o pipefail
shopt -s -o errexit
shopt -s extglob

# Program Variables
#___________________________________________________________________________________________________
declare -r scriptName=${0##*/}
declare -r path="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
declare -r options="b:hk:r:"
declare optionResult=""
declare -r projectName="pecunia"
declare version=""
declare keyId=""
declare -r debBuildDirectoryPath="$HOME/debbuild"
declare tarballFileName=""
declare tarballOrigFileName=""
# licence in copyright file (apache|artistic|bsd|gpl|gpl2|gpl3|isc|lgpl|lgpl2|lgpl3|mit|custom)
declare -r licence="lgpl3"
# single, indep (arch-independent), library, python
declare -r packageclass="library"
declare branch=""
declare release=0

# Program Argument Validation
#___________________________________________________________________________________________________
while getopts "${options}" optionResult
do
	case ${optionResult} in
	b)  # Set Branch Name
		branch="$OPTARG"
		;;
	h)  # Show help
		printf "usage: ${scriptName} [options]\n"
		printf "Options:\n"
		printf "  -b <name>       Sets the name of the branch to package.\n"
		printf "  -k <id>         Sets the ID of the sign key.\n"
		printf "  -r <release>    Sets the package release number.\n"
		exit 0
		;;
	k)  # Set Key Sign ID
		keyId="$OPTARG"
		;;
	r)  # Set Package Release Number
		release="$OPTARG"
		;;
	\?)
		exit 2
		;;
	*)
		printf "Unknown option: ${optionResult}\n" 1>&2
		exit 2
		;;
	esac
done

if [[ -z "${keyId}" ]]
then
	echo "The ID for the signing key must be specified."
	exit 1
fi

if [[ -z "${branch}" ]]
then
	echo "The branch name of ${projectName} must be specified." 1>&2
	exit 1
fi

if (( ${release} <= 0 ))
then
	echo "The package release number is missing or not a number." 1>&2
	exit 1
fi


# Program Execution
#___________________________________________________________________________________________________
pushd "$path/.."
version=$(grep VERSION CMakeLists.txt | tail -1 | awk '{ print $2 }')

if [[ -z "${version}" ]]
then
	echo "Failed to determine the version of ${projectName}."
	exit 1
else
	echo "Determine the version of ${projectName} to be ${version}."
	tarballFileName="${projectName}-${version}.tar"
	tarballOrigFileName="${projectName}_${version}.orig.tar.xz"
fi

echo "Generating project tarball..."
hg pull
hg update --clean --rev "${branch}"
hg archive "${tarballFileName}" --rev "${branch}"

if [[ ! -e "${debBuildDirectoryPath}/" ]]
then
	mkdir "${debBuildDirectoryPath}/"
fi
mv "${tarballFileName}" "${debBuildDirectoryPath}/"

echo "Generating Debian file structure..."
cd "${debBuildDirectoryPath}"
tar -xf "${tarballFileName}"
cd "${projectName}-${version}/"

if [[ -e "${debBuildDirectoryPath}/${projectName}-${version}/pkg/debian" ]]
then
	mv "${debBuildDirectoryPath}/${projectName}-${version}/pkg/debian" .
	xz "../${tarballFileName}"
	mv "../${tarballFileName}.xz" "../${tarballOrigFileName}"
else
	dh_make \
		--yes  \
		--copyright ${licence}  \
		--${packageclass}  \
		--createorig
fi
echo "Updating package version information..."
sed -i "s/@@BINARY_VERSION@@/${version}/" debian/changelog
sed -i "s/@@PACKAGE_RELEASE@@/${release}/" debian/changelog
sed -i "s/@@BUILD_TIME@@/$(date --rfc-email)/" debian/changelog
sed -i "s/@@BINARY_VERSION@@/${version}/g" debian/shlibs.local

echo "Building DEB package..."
export BINARY_VERSION="${version}" &&  \
	export PACKAGE_RELEASE="${release}" &&  \
	dpkg-buildpackage -us -uc

echo "Signing DEB package..."
debsign -k${keyId}

echo "Cleaning up temporary build files..."
cd ..
rm --recursive --dir "${projectName}-${version}/"

if [[ -e "${tarballFileName}" ]]
then
	rm "${tarballFileName}"
fi

echo "Successfully created DEB package."

