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

# Install deps
sudo apt install -y \
	dh-autoreconf \
	dh-make \
	check \
	util-linux \
	libblkid-dev \
	git \
	dracut-core

# Set github user and project name
USER="dracut-crypt-ssh"
PROJECT="dracut-crypt-ssh"
LICENSE="gpl2" # Adjust based on the actual license
SECTION="admin"
HOMEPAGE="https://github.com/dracut-crypt-ssh/dracut-crypt-ssh"
BUILD_HOME="/var/tmp/dracut-crypt-ssh-git_build"
PACKAGE="dracut-crypt-ssh"
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="A dracut module for unlocking encrytpted systems via ssh."
LONG_DESCRIPTION="dracut-crypt-ssh allows remote unlocking of systems with full disk encryption via ssh, providing a way of entering encryption keys for servers without console switching and allowing booting of remote or co-located encrypted servers without console access."

# 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

# a config.mk is missing but may be added.
sed -i 's/^include config.mk/-include config.mk/' Makefile

mkdir -p m4

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

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

BUILD_OPTIONS="" # Adjust based on the build system of the dracut-crypt-ssh project

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

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/ \
 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
