#!/usr/bin/env bash
set -x
ARCH=amd64
# DEPENDENCIES="python3-neovim fd-find ripgrep"
readarray -t DEPENDENCIES <<-EOF
	python3-neovim
	fd-find
	ripgrep
	luarocks
EOF

USER="neovim"
PROJECT="neovim"
BRANCH=$(lastversion --format=tag ${PROJECT})
PACKAGE="neovim"
DEBVERSION=$(lastversion ${PROJECT})
DEBEMAIL="person@company.tld"
DEBFULLNAME="Testy McTester"
DESCRIPTION="hyperextensible Vim-based text editor"
SECTION="admin"
HOMEPAGE="https://neovim.io/"
# LICENSE="apache2"

# install debian dependencies
sudo apt-get install -y "${DEPENDENCIES[@]}"

# clone the repository
git clone --branch "${BRANCH}" "https://github.com/${USER}/${PROJECT}.git" --depth 1 "${PACKAGE}-${DEBVERSION}"

# debianize the cloned repository
cd "${PACKAGE}-${DEBVERSION}" || exit
dh_make --createorig --single --native --yes

# set the user's full name and email address
sed -i "s,^\(Maintainer: \).*,\1'${DEBFULLNAME}\ \<${DEBEMAIL}\>'," debian/control

# 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,^\(Homepage: \).*,\1'${HOMEPAGE}',' debian/control

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

# build the Debian package
dpkg-buildpackage -us -uc -b

# install the Debian package
sudo dpkg -i "../${PACKAGE}_${DEBVERSION}_${ARCH}.deb"
