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

# Install deps
sudo apt install -y \
	meson \
	ninja-build \
	libwayland-dev \
	libwayland-egl-backend-dev \
	libwayland-client-dev \
	libwayland-server-dev \
	wayland-protocols \
	wayland-scanner \
	git

# Set github user and project name
USER="hyprwm"
PROJECT="hyprland-protocols"
LICENSE="bsd"
SECTION="x11/wm"
HOMEPAGE="https://github.com/hyprwm/hyprland-protocols"
BUILD_HOME="/var/tmp/hyprland-protocols-git_build"
PACKAGE="hyprland-protocols"
VERSION=$(curl "https://api.github.com/repos/${USER}/${PROJECT}/tags?per_page=5" | jq -r '.[0] | .name')
VERSION=${VERSION:1} # strip the preceding 'v'
DEBEMAIL="cyteen@ring-zero.co.uk"
DEBFULLNAME="Cyteen May"
DESCRIPTION="Hyprland Protocols, Wayland protocols used by Hyprland."
LONG_DESCRIPTION="This repository holds protocols used by Hyprland to bridge the gap between Hyprland and KDE/Gnome's functionality. It includes protocols for exporting toplevel buffers for screensharing and managing global keybinds via D-Bus."

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

git clone https://github.com/${USER}/${PROJECT}.git ${PACKAGE}-${VERSION}

cd ${PACKAGE}-${VERSION} || exit

# debianize the BUILD_HOME directory
dh_make \
	--createorig \
	--single \
	--native \
	--copyright ${LICENSE} \
	--yes

# Customize the debian directory values
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
sed -i "s|.*insert long.*|${LONG_DESCRIPTION}|" debian/control

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

%:
	dh $@

override_dh_auto_configure:
	dh_auto_configure -- \
	-Ddefault_library=both
EOF

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

dpkg-buildpackage -us -uc -b

echo ${PACKAGE}_${VERSION}_amd64.deb

sudo dpkg -i ../${PACKAGE}_${VERSION}_amd64.deb
