#*******************************************************************************
#**  This file is part of Dux Rei Nummariae.                                 ***
#**                                                                          ***
#**  Copyright (C) 2017, 2018, 2019, 2020, 2021                              ***
#**  John Schneiderman <Licensing _AT_ Schneiderman _DOT_ me>                ***
#**                                                                          ***
#**  This program is free software: you can redistribute it and/or modify it ***
#**  under the terms of the GNU Affero 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 Affero General Public License for more details.             ***
#**                                                                          ***
#**  You should have received a copy of the GNU Affero General Public License***
#**  along with this program. If not, see <http://www.gnu.org/licenses/>.    ***
#*******************************************************************************

#!/usr/bin/env bash
shopt -s -o nounset  # Don't allow the use of variables that haven't been declared
shopt -s -o pipefail # This option sets the exit code of a pipeline to that of the rightmost
					 # command to exit with a non-zero status, or zero if all commands of the
					 # pipeline exit successfully.
shopt -s -o errexit  # Exit when a command fails
shopt -s extglob  # Allow the use of the extra pattern

# Program Variables
#___________________________________________________________________________________________________
declare -r scriptName=${0##*/}
declare -r path="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
declare -r options="a:hk:v:"
declare optionResult=""
declare -r projectName="duxreinummariae"
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="custom"
# single, indep (arch-independent), library, python
declare -r packageclass="single"
declare apiKey=""

# Program Argument Validation
#___________________________________________________________________________________________________
while getopts "${options}" optionResult
do
	case ${optionResult} in
	a)  # Set API key
		apiKey="$OPTARG"
		;;
	h)  # Show help
		printf "usage: ${scriptName} [options]\n"
		printf "Options:\n"
		printf "  -a <key>        Sets the API key for currency updates.\n"
		printf "  -k <id>         Sets the ID of the sign key.\n"
		printf "  -v <version>    Sets the version to package.\n"
		exit 0
		;;
	k)  # Set Key Sign ID
		keyId="$OPTARG"
		;;
	v)  # Set Package Version
		version="$OPTARG"
		;;
	\?)
		exit 2
		;;
	*)
		exit 2
		;;
	esac
done

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

if [[ -z "${version}" ]]
then
	echo "The version of ${projectName} must be specified."
	exit 1
fi


# Program Execution
#___________________________________________________________________________________________________
tarballFileName="${projectName}-${version}.tar"
tarballOrigFileName="${projectName}_${version}.orig.tar.xz"
cd "$path/.."

echo "Generating project tarball..."
hg archive "${tarballFileName}" -r "${version}" || exit $?

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

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

if [[ -e "${debBuildDirectoryPath}/${projectName}-${version}/pkg/debian" ]]
then
	mv "${debBuildDirectoryPath}/${projectName}-${version}/pkg/debian" . || exit $?
	xz "../${tarballFileName}" || exit $?
	mv "../${tarballFileName}.xz" "../${tarballOrigFileName}" || exit $?
else
	dh_make \
		--yes  \
		--copyright ${licence}  \
		--${packageclass}  \
		--createorig  \
		|| exit $?
fi

echo "Building DEB package..."
export CURRENCY_API_KEY="${apiKey}" \
	&& dpkg-buildpackage -us -uc || exit $?

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

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

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

echo "Successfully created DEB package."

