#!/usr/bin/env bash
set -x

ARCH="${1:-amd64}"
#ARCH=armhf

PATH=/root/.local/bin:$PATH

# install debian dependencies
DEPENDENCIES="jq dh-make python3-flake8 python3-wheel"
sudo apt install -y ${DEPENDENCIES}
# pipx install ruff

echo "FIXME: The test suite in the package build is disabled as it currently fails, check that they pass before rebuiding."

USER="kislyuk"
PROJECT="yq"
# LICENSE="mit"
LICENSE="gpl"
SECTION="admin"
HOMEPAGE="https://kislyuk.github.io/yq/"
BUILD_HOME="/var/tmp/yq-git_build"
PACKAGE="yq"
VERSION=$(curl "https://api.github.com/repos/${USER}/${PROJECT}/tags?per_page=5" | jq -r '.[0] | .name')
DEBVERSION=${VERSION:1} # strip the preceding 'v'
DEBEMAIL="person@company.tld"
DEBFULLNAME="Testy McTester"
DESCRIPTION="Command-line YAML and XML processor."
LONG_DESCRIPTION=" Command-line YAML and XML processor\\n jq wrapper for YAML/XML documents."

RSS_FEED="https://github.com/${USER}/${PROJECT}/releases.atom"
# xdg-open ${RSS_FEED}
echo ${RSS_FEED}

# Make the BUILD_HOME directory and clone upstream
mkdir -p ${BUILD_HOME}
cd ${BUILD_HOME} || exit

#git clone http://github.com/${USER}/${PROJECT}.git ${PACKAGE}-${VERSION}
git clone --branch ${VERSION} http://github.com/${USER}/${PROJECT}.git --depth 1 ${PACKAGE}-${DEBVERSION}

cd ${PACKAGE}-${DEBVERSION} || exit
git checkout tags/${VERSION}

mkdir -p m4

cat <<-EOF >.git/gbp.conf
	[DEFAULT]
	# this is the upstream-branch:
	upstream-branch=master
EOF

# debianize the BUILD_HOME directory
echo ${DEBFULLNAME}
USER=root dh_make \
	--createorig \
	--single \
	--native \
	--email ${DEBEMAIL} \
	--copyright ${LICENSE} \
	--yes

cp README.rst debian/README
rm debian/README.source

# Customize the debian directory values
sed -i 's,^\(Description: \).*,\1'${DESCRIPTION}',' debian/control
sed -i "s,^\(Description: \).*,\1${DESCRIPTION}," debian/control
sed -i 's,^\(Section: \).*,\1'${SECTION}',' debian/control
sed -i "s,^\(Maintainer: \).*,\1'${DEBFULLNAME}\ \<${DEBEMAIL}\>'," debian/control
sed -i 's,^\(Homepage: \).*,\1'${HOMEPAGE}',' debian/control

PLACEHOLDER=" <insert long description, indented with spaces>"
sed -i 's|'"${PLACEHOLDER}"'|'"${LONG_DESCRIPTION}"'|g' debian/control

echo ****************
cat debian/control
echo ****************

#BUILD_OPTIONS="--enable-aac --enable-ofono --enable-debug"
BUILD_OPTIONS="--buildsystem=none"

cat <<EOF >debian/rules
#!/usr/bin/make -f
%:
	dh \$@

override_dh_auto_test:
	echo "Skipping tests."
#	-dh_auto_test

override_dh_auto_configure:
	dh_auto_configure -- ${BUILD_OPTIONS}
EOF

cat <<-EOF >debian/watch
	version=4
	opts=filenamemangle=s/.+\/v?(\d\S+)\.tar\.gz/${PROJECT}-$1\.tar\.gz/ \
	  http://github.com/${USER}/${PROJECT}/tags .*/v?(\d\S+)\.tar\.gz
EOF

sudo -EH dpkg-buildpackage -us -uc -b

echo ${PACKAGE}_${DEBVERSION}_${ARCH}.deb

sudo dpkg -i ../${PACKAGE}_${DEBVERSION}_${ARCH}.deb
