#!/bin/sh

# SPDX-FileCopyrightText: 2024 KUNBUS GmbH
#
# SPDX-License-Identifier: GPL-2.0-or-later

# Take the upstream version, derive the package version and generate the
# "debian/" folder.
#
# $1: upstream version, including tag
# output: populated "debian/" folder

set -e

: ${KBUILD_BUILD_HOST:=kunbus.com}
: ${KBUILD_BUILD_USER:=support}
: ${DEBEMAIL:="${KBUILD_BUILD_USER}@${KBUILD_BUILD_HOST}"}
: ${DEBFULLNAME:="KUNBUS GmbH"}
: ${ARCH:=arm64}
: ${RELEASE:=bookworm}
: ${DEBIAN_VERSION:=12}
: ${RPI_ARCH_SUFFIX:=-v8}

VERBOSITY=0
EXTRA_MAKE_OPTS=""
# v${MAINLINE_VER}-revpi${REVPI_VER}
# the (.*) indicates that the upstream version can be appended with snapshot-specific string
UPSTREAM_VERS_REGEX='^v\([[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+\)-revpi\([[:digit:]]\+\).*'
FORCE_CHANGELOG_GEN=""
LINTIAN_OVERRIDES_FILE="debian/source/lintian-overrides"

usage() {
	cat <<- __EOF__
	usage: $(basename "$0"): [-a deb_rev_append] [-cd] [-v...] UPSTREAM_VERSION

	Generate the "debian/" directory for the linux kernel.
	Execute this script in the root of the kernel source tree.

	Options:
	  -a    Append additional string to the debian revision
	  -c    Generate a new debian/changelog and override the old one if present
	  -d    Upstream is a "devel/" branch
	  -l    Write a default debian/copyright file
	  -v    Be verbose. Pass multiple times for increased verbosity
	        Uses "set -x" and sets "KBUILD_VERBOSE=1"

	Arguments:
	  UPSTREAM_VERSION    The upstream version of the project, formatted as
	                      "v\${MAINLINE_VER}-revpi\${REVPI_VER}"
	                      Additionally, an arbitrary string can be appended,
	                      e.g. when building a snapshot.
	__EOF__

	exit "${1:-0}"
}

while getopts "a:cdhlv" opt; do
	case "$opt" in
	a) deb_rev_append="$OPTARG" ;;
	c) FORCE_CHANGELOG_GEN="true" ;;
	d) DEVEL_BRANCH="devel/" ;;
	h) usage 0 ;;
	l) FORCE_COPYRIGHT_GEN="true" ;;
	v) VERBOSITY=$((VERBOSITY+1)) ;;
	?) usage 1 >&2 ;;
	esac
done

shift $((OPTIND - 1))

if [ $# -lt 1 ]; then
	printf "Invalid number of arguments given\n" >&2
	usage 1 >&2
fi

upstream_version=$1

[ $VERBOSITY -gt 0 ] && set -x
[ $VERBOSITY -gt 1 ] && EXTRA_MAKE_OPTS="KBUILD_VERBOSE=1"

if ! expr "$upstream_version" : "$UPSTREAM_VERS_REGEX" >/dev/null; then
	printf "Invalid upstream version\n" >&2
	usage 1 >&2
fi

mainline_vers="$(printf "%s\n" "$upstream_version" \
	| sed -e "s/$UPSTREAM_VERS_REGEX/\1/")"
revpi_vers="$(printf "%s\n" "$upstream_version" \
	| sed -e "s/$UPSTREAM_VERS_REGEX/\2/")"
upstream_vers="${upstream_version#v}"

pkg_name_ext="${mainline_vers}-revpi${revpi_vers}-rpi${RPI_ARCH_SUFFIX}"
pkg_vers="${upstream_vers}-1+deb${DEBIAN_VERSION}+1${deb_rev_append}"

# export variables so kbuild knows about them, too
export ARCH FORCE_CHANGELOG_GEN FORCE_COPYRIGHT_GEN
set -- \
	KBUILD_BUILD_HOST="$KBUILD_BUILD_HOST" \
	KBUILD_BUILD_USER="$KBUILD_BUILD_USER" \
	KERNELRELEASE="$pkg_name_ext" \
	KDEB_PKGVERSION="$pkg_vers" \
	KDEB_SOURCENAME=linux-revpi"$RPI_ARCH_SUFFIX" \
	KDEB_CHANGELOG_DIST="$RELEASE" \
	DEBEMAIL="$DEBEMAIL" \
	DEBFULLNAME="$DEBFULLNAME" \
	$EXTRA_MAKE_OPTS \
	--jobs=$(nproc)

make "$@" revpi"${RPI_ARCH_SUFFIX}"_defconfig
make "$@" run-command \
	KBUILD_RUN_COMMAND='$(srctree)/scripts/package/mkdebian --need-source'

cat << EOF > debian/.gitignore
files
*.files
linux-headers/
linux-headers-*/
linux-image/
linux-image-*/
linux-libc-dev/
*.substvars

!patches/
!patches/*.patch
!patches/series
EOF

cat <<- __EOF__ > "$LINTIAN_OVERRIDES_FILE"
# The copyright notice in the GFDL itself, mentioning invariant sections, is
# just an example. lintian seems to whitelist the plain-text version but that
# doesn't cover this ReST version.
__EOF__

for file in \
	Documentation/userspace-api/media/v4l/pixfmt-meta-bcm2835-isp-stats.rst \
	Documentation/userspace-api/media/v4l/pixfmt-meta-sensor-data.rst \
	Documentation/userspace-api/media/v4l/pixfmt-nv12-col128.rst \
	Documentation/userspace-api/media/v4l/pixfmt-y12p.rst \
	Documentation/userspace-api/media/v4l/pixfmt-y14p.rst
do
	cat <<- __EOF__ >> "$LINTIAN_OVERRIDES_FILE"
	linux-revpi-v8 source: license-problem-gfdl-invariants \
invariant part is: published by the free software .. foundation, with no \
invariant sections, no front-cover texts .. and no back-cover texts \
[$file]
	__EOF__
done

cat <<- __EOF__ >> "$LINTIAN_OVERRIDES_FILE"
linux-revpi-v8 source: license-problem-gfdl-invariants invariant part is: with \
the :ref:\`invariant sections <fdl-invariant>\` being list their titles, with \
the :ref:\`front-cover texts <fdl-cover-texts>\` being list, and with the \
:ref:\`back-cover texts <fdl-cover-texts>\` being list \
[Documentation/userspace-api/media/fdl-appendix.rst]

# The custom compression is opt-in for local and test builds. Giving the option
# is okay.
linux-revpi-v8 source: custom-compression-in-debian-rules

# These executables are test cases and source is provided
linux-revpi-v8 source: \
source-contains-prebuilt-windows-binary [tools/perf/tests/pe-file.exe.debug]
linux-revpi-v8 source: \
source-contains-prebuilt-windows-binary [tools/perf/tests/pe-file.exe]
__EOF__

# The binary packages linux-image-*-dbg and linux-headers-* both have long
# names that lintian complains about. Override lintian to ignore this as they
# can't be shorter.
linux_lintian_name_common="${mainline_vers}-revpi${revpi_vers}-rpi${RPI_ARCH_SUFFIX}"
linux_image_dbg_lintian=debian/linux-image-"${linux_lintian_name_common}"-dbg.lintian-overrides
linux_headers_lintian=debian/linux-headers-"${linux_lintian_name_common}".lintian-overrides

cat <<- __EOF__ >> "$LINTIAN_OVERRIDES_FILE"
linux-revpi-v8 source: dbg-package-missing-depends \
linux-image-$linux_lintian_name_common-dbg
__EOF__

# make sure no overrides for possibly old versions are present
rm -f debian/*.lintian-overrides
for file in \
	"${linux_image_dbg_lintian}" \
	"${linux_headers_lintian}"
do
	cat <<- __EOF__ > "$file"
	# Ignore the warning because the file names for the headers and image can't be
	# shorter than they are due to the following constraints:
	# - "rpi" needs to be in the name
	# - version string needs to be in the name, consists of:
	#   - mainline version (i.e. 6.6.0)
	#   - revpi version (i.e. revpi5)
	package-has-long-file-name
	__EOF__
done

cat > debian/gbp.conf <<- __EOF__
[DEFAULT]
upstream-branch = ${DEVEL_BRANCH}revpi-${mainline_vers%.*}
upstream-tag = v%(version)s
debian-branch = debian/$RELEASE
debian-tag = debian/%(version)s
debian-tag-msg = %(pkg)s Debian release %(version)s
pristine-tar = True
builder = debuild --preserve-envvar KBUILD_BUILD_\* -i -I
__EOF__
