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

# Install deps
sudo apt install -y \
  cmake \
  dh-cmake \
  git \
  build-essential \
  libcairo2 \
  libcairo2-dev \
  libzip4 \
  libzip-dev \
  librsvg2-2 \
  librsvg2-dev

# Set github user and project name
USER="hyprwm"
PROJECT="hyprutils"
LICENSE="gpl3"
HOMEPAGE="https://github.com/hyprwm/hyprlang"
BUILD_HOME="/var/tmp/hyprlang-git_build"
PACKAGE="hyprutils"
VERSION=$(curl "https://api.github.com/repos/${USER}/${PROJECT}/tags?per_page=5" | jq -r '.[0] | .name')
VERSION=${VERSION:1} # strip the preceding 'v'
SECTION="x11/wm"
DEBEMAIL="cyteen@ring-zero.co.uk"
DEBFULLNAME="Cyteen May"
DESCRIPTION="A small C++ library for utilities in the Hypr* ecosystem."
LONG_DESCRIPTION="Hyprutils is a small C++ library for utilities used across the Hypr* ecosystem."

# 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

# Uncomment and adjust the following lines as needed
#export DH_VERBOSE = 1
#export DEB_BUILD_MAINT_OPTIONS = hardening=+all
#export DEB_CFLAGS_MAINT_APPEND = -Wall -pedantic
#export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed

%:
	dh $@ --buildsystem=cmake

override_dh_auto_configure:
	dh_auto_configure -- \
	-DCMAKE_INSTALL_PREFIX=/usr \
  -DCMAKE_BUILD_TYPE=Release \
	-DCMAKE_LIBRARY_ARCHITECTURE="$(DEB_HOST_MULTIARCH)"
EOF

# Build and install Hyprlang using CMake
# cmake --no-warn-unused-cli -DCMAKE_BUILD_TYPE:STRING=Release -DCMAKE_INSTALL_PREFIX:PATH=/usr -S . -B ./build
# cmake --build ./build --config Release --target all -j$(nproc 2>/dev/null || getconf NPROCESSORS_CONF)
# sudo cmake --install build

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
