apt install -y jq

set -x
PROJECT=onivim/oni2
USER="onivim"
PROJECT="oni2"
LICENSE="gpl3"
SECTION="development"
HOMEPAGE="https:/v2.onivim.io/"
BUILD_HOME="/var/tmp/onivim2-git_build"
PACKAGE="onivim2"
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="An editor that aims to bring the speed of Sublime, the language integration of VSCode, and the modal editing experience of Vim together, in a single package."

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 --branch ${VERSION} http://github.com/${USER}/${PROJECT}.git --depth 1 ${PACKAGE}-${DEBVERSION}

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

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 \
	--indep \
	--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="--buildsystem=none"

# build dependencies: git, node, esy (like npm for native code: Reason, OCaml...)
# http://github.com/revery-ui/revery/wiki/Building-&-Installing
# apt install nodejs npm

cat <<EOF >debian/rules
#!/usr/bin/make -f

package=onivim2

%:
	dh $@

override_dh_auto_build:
	export GRADLE_OPTS="-Dorg.gradle.daemon=false -Xmx512m"; \
	dh_auto_build -- assemble

#override_dh_install:
#	dh_auto_build -- installDist -x test;

#override_dh_clean:
#	dh_auto_build -- clean

get-orig-source:
	uscan --verbose --repack --compression xz --download-current-version --force-download
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

dpkg-buildpackage -us -uc -b

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

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