#!/usr/bin/env bash
# bump dist-kernels
# (c) 2022-2026 Michał Górny <mgorny@gentoo.org>
# SPDX-License-Identifier: GPL-2.0-or-later

set -x -e

shopt -s extglob

scriptdir=${BASH_SOURCE%/*}
cd "$(git rev-parse --show-toplevel)"

NEWEST_GENTOO_CONFIG_P=$(
	grep -h "^GENTOO_CONFIG_P=" sys-kernel/{gentoo,vanilla}-kernel/*.ebuild |
		sort -V | tail -n 1
)

if [[ ${#} -eq 0 ]]; then
	set -- $("${scriptdir}"/get-kernel-slots)
fi

for arg; do
	if [[ ${arg} == *:* ]]; then
		old_full=${arg%:*}
		new_full=${arg#*:}
	else
		old_full=${arg}*
		new_full=+1
	fi

	for pkg in vanilla-kernel gentoo-kernel; do
		old=${old_full}
		new=${new_full}
		if [[ ${pkg} == vanilla-kernel ]]; then
			old=${old%_p*}
			new=${new%_p*}
		fi
		[[ ${old} == ${new} ]] && continue

		(
			cd sys-kernel/${pkg}
			oldk=${pkg}-${old}.ebuild
			newk=${new}
			if [[ ${newk} != +* ]]; then
				newk=${pkg}-${newk}.ebuild
			fi
			"${scriptdir}"/pkgbump -M -D "${oldk}" "${newk}"
			if [[ ${newk} == +* ]]; then
				newk=${pkg}-$(<.pkgbump-pv).ebuild
			fi
			[[ ${old_full%_p*} != ${new_full%_p*} ]] &&
				sed -i -e "s:^\(SHA256SUM_DATE=\).*:\1$(date +%Y%m%d):" "${newk}"
			sed -i -e "s:^GENTOO_CONFIG_P=.*$:${NEWEST_GENTOO_CONFIG_P}:" "${newk}"
			${EDITOR:-vim} "${newk}"
			GENTOO_MIRRORS= ebuild "${newk}" manifest

			if [[ ${pkg} != vanilla-kernel ]]; then
				# do verify-sig & test patching
				USE="experimental verify-sig" ebuild "${newk}" prepare
				ebuild "${newk}" clean &
			fi

			git add Manifest "${newk}"
			"${scriptdir}"/pkgcommit -sS . --bump
		)
	done

	(
		pkg=dist-kernel
		cd "virtual/${pkg}"
		oldk=${pkg}-${old_full}.ebuild
		newk=${new_full}
		if [[ ${newk} != +* ]]; then
			newk=${pkg}-${newk}.ebuild
		fi
		"${scriptdir}"/pkgbump -M -D -c "${oldk}" "${newk}"
	)

	git diff origin > ${BINPKG_DOCKER:-~/git/binpkg-docker}/local.diff
done

while wait -n; do :; done
