#!/bin/sh
# SPDX-License-Identifier: GPL-2.0-or-later
# SPDX-FileCopyrightText: 2024-2025 KUNBUS GmbH
#
# This script generates the ./debian/control file and some extra files for the
# piControl debianization. It should be used to update the debianization for
# every new release. This includes rebuilding piControl for new kernels even
# if piControl itself hasn't changed.
#
# The ./debian/control file is recreated and overwritten.
# The ./debian/changelog is extended with a new changelog entry.

set -e

# This is the major version of the Debian distribution
# Bullseye: 11, Bookworm: 12, Trixie: 13, ...
DISTRO_VERSION=12

usage() {
	cat <<- __EOF__
	usage: $(basename "$0"): [-h] UPSTREAM_VERSION KERNEL_PKG_VERSION

	Generate the "debian/control" file and version dependent files.
	Execute this script in the root of the piControl source directory.

	Options:
	  -h    display this help and exit

	Arguments:
	  UPSTREAM_VERSION    The upstream piControl version, formatted as
	                      "v\${MAJOR}.\${MINOR}.\${PATCH}"
	  KERNEL_PKG_VERSION  The version of the kernel package, e.g.
	                      "6.6.23-rt27-revpi0-1+deb12+1"
	__EOF__

	exit "${1:-0}"
}

while getopts "h" opt; do
	case "$opt" in
	h) usage 0 ;;
	?) usage 1 >&2 ;;
	esac
done

shift $((OPTIND - 1))

if [ $# -lt 2 ]; then
	echo "ERROR: Invalid number of arguments given" >&2
	usage 1 >&2
fi

picontrol_ver="${1#v}"
kernel_pkg_ver="$2"
debdir=./debian

if [ ! -d "$debdir" ]; then
	echo "ERROR: $debdir not found." >&2
	exit 1
fi

# Some helper functions to help with debian version string handling.
# Also create some variables DEB_* which run these helpers on the current
# version from the debian/changelog file.
# See /usr/share/dpkg/pkg-info.mk for details
deb_source() {
	dpkg-parsechangelog -SSource
}
DEB_SOURCE="$(deb_source)"

deb_version() {
	dpkg-parsechangelog -SVersion
}
DEB_VERSION="$(deb_version)"

deb_version_epoch() {
	version="$1"
	epoch="${version%%:*}"
	[ "$version" = "$epoch" ] && epoch=""
	echo "$epoch"
}
DEB_VERSION_EPOCH="$(deb_version_epoch "$DEB_VERSION")"

deb_str_version_epoch_upstream() {
	echo "$1" | sed -e 's/-[^- ]*$//'
}
DEB_VERSION_EPOCH_UPSTREAM="$(deb_str_version_epoch_upstream "$DEB_VERSION")"

deb_str_version_upstream_revision() {
	echo "$1" | sed -e 's/^[0-9]*://'
}
DEB_VERSION_UPSTREAM_REVISION="$(deb_str_version_upstream_revision "$DEB_VERSION")"

deb_str_version_upstream() {
	echo "$1" | sed -e 's/^[0-9]*://'
}
DEB_VERSION_UPSTREAM="$(deb_str_version_upstream "$DEB_VERSION_EPOCH_UPSTREAM")"

deb_version_pkg_revision() {
	echo "${1##*+}"
}
DEB_VERSION_PKG_REVISION="$(deb_version_pkg_revision "$DEB_VERSION")"

deb_distribution() {
	dpkg-parsechangelog -SDistribution
}
DEB_DISTRIBUTION="$(deb_distribution)"

if [ "$DEB_DISTRIBUTION" = "UNRELEASED" ]; then
	echo "ERROR: The distribution field in the changelog is set to UNRELEASED." >&2
	exit 1
fi

# Variables related to the kernel (package)
# version of the kernel package without epoch
kernel_pkg_no_epoch="$(deb_str_version_upstream_revision "$kernel_pkg_ver")"

# the upstream version part of the kernel package version
kernel_upstream_ver="$(deb_str_version_upstream "$kernel_pkg_no_epoch")"

# the mainline version part of the kernel package version
kernel_mainline_ver="${kernel_upstream_ver%%-*}"

# the rt version part of the kernel package version (currently unused)
#kernel_rt_ver=$(echo "$kernel_upstream_ver" | sed -e 's/.*-rt\([0-9]\+\)-.*/\1/')
# the revpi version part of the kernel package version
kernel_revpi_ver="$(echo "$kernel_upstream_ver" | sed -e 's/.*-revpi\([0-9]\+\).*/\1/')"

# The kernel package has a version component added to the package names.
# The variable $pkg_append derives this component from the kernel version.
pkg_append="${kernel_mainline_ver}-revpi${kernel_revpi_ver}-rpi-v8"

# The package revision (the last +N) is incremented if the upstream version read
# from the changelog and the given upstream version are the same. This means the
# package is rebuilt with the same piControl version.
if [ "$DEB_VERSION_UPSTREAM" = "$picontrol_ver" ]; then
	pkg_ver_new="${DEB_VERSION%+*}+$((DEB_VERSION_PKG_REVISION + 1))"
else
	pkg_epoch=''
	[ -n "$DEB_VERSION_EPOCH" ] && pkg_epoch="${DEB_VERSION_EPOCH}:"
	pkg_ver_new="${pkg_epoch}${picontrol_ver}-1+deb${DISTRO_VERSION}+1"
fi

cat <<- EOF > "$debdir/control"
	# DO NOT EDIT THIS FILE!
	# This file is generated and all changes will be overwritten

	Source: picontrol
	Section: kernel
	Priority: optional
	Maintainer: KUNBUS GmbH <support@kunbus.com>
	Build-Depends:
	  debhelper-compat (= 13),
	  dh-sequence-dkms,
	  linux-headers-${pkg_append} (= ${kernel_pkg_ver}),
	Standards-Version: 4.6.2
	Homepage: https://revolutionpi.com/
	Rules-Requires-Root: no
	Vcs-Git: https://gitlab.com/revolutionpi/piControl.git -b debian/bookworm
	Vcs-Browser: https://gitlab.com/revolutionpi/piControl/

	Package: picontrol-${pkg_append}
	Architecture: any
	Depends:
	  linux-image-${pkg_append} (= ${kernel_pkg_ver}),
	  picontrol-common,
	  \${misc:Depends},
	Conflicts: picontrol-dkms
	Description: RevPi piControl kernel module package
	 piControl is a kernel module for interfacing with RevPi hardware. It
	 provides a common interface to all RevPi related IOs, which a user can
	 consume via /dev/piControl0.
	 .
	 This package is built for linux-image-${pkg_append}
	 (= ${kernel_pkg_ver}).

	Package: picontrol-common
	Architecture: all
	Depends:
	  \${misc:Depends},
	Breaks: picontrol-dkms (<< 2.1.3-2)
	Replaces: picontrol-dkms (<< 2.1.3-2)
	Description: RevPi piControl kernel module package (common files)
	 This package contains architecture independent files like udev rules
	 and the modules-load.d configuration to automatically load piControl
	 on boot.

	Package: picontrol
	Architecture: any
	Depends:
	  picontrol-${pkg_append} (= \${binary:Version}),
	  \${misc:Depends},
	Description: RevPi piControl kernel module package (metapackage)
	 piControl is a kernel module for interfacing with RevPi hardware. It
	 provides a common interface to all RevPi related IOs, which a user can
	 consume via /dev/piControl0.

	Package: picontrol-dkms
	Architecture: all
	Depends:
	  picontrol-common,
	  \${misc:Depends},
	Conflicts: picontrol
	Description: piControl driver for Revolution Pi extension modules
	 Revolution Pi is a set of IoT products based on the Raspberry Pi and
	 geared towards industrial usage.
EOF

cat <<- EOF > "$debdir/rules.vars"
	KERNELRELEASE := ${pkg_append}
EOF

dch --newversion "$pkg_ver_new" \
	"Build for linux-image-${pkg_append} (= ${kernel_pkg_ver})"

cat <<- EOF > ./commit-msg.txt
	Release $DEB_SOURCE ${pkg_ver_new}

	Build for linux-image-${pkg_append} (= ${kernel_pkg_ver})
EOF
