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

shopt -s extglob

check_valid() {
	if [[ ${1} != *.ebuild ]]; then
		echo "Incorrect filename: ${1}"
		exit 1
	fi

	filename=${1##*/}
	version=$(patom -F '%{fullver}' "=category/${1%.ebuild}")
	if [[ -z ${version} ]]; then
		echo "Incorrect filename: ${1}"
		exit 1
	fi
}

from_arg_to_filename() {
	local arg=${1}

	if [[ ! -f ${arg} ]]; then
		local ebuilds
		mapfile -t ebuilds < <(printf '%s\n' ${arg} | sort -r -V)
		set -- "${ebuilds[@]}"

		# skip live ebuilds
		while [[ ${1} == *9999* ]]; do shift; done
		[[ -n ${1} ]] && arg=${1}
	fi

	echo "${arg}"
}

version_arg_to_filename() {
	local arg=${1}
	local reference=${2}

	reference=${reference%.ebuild}
	reference=${reference%-r+([0-9])}

	if [[ ${arg} == +* ]]; then
		refv=.${reference##*-}
		suffix=

		while [[ ${arg} == *.* ]]; do
			refv=${refv%.*}
			suffix=.${arg##*.}${suffix}
			arg=${arg%.*}
		done

		oldv=${refv##*.}
		arg=${refv%.*}.$(( oldv + ${arg#+} ))${suffix}
		arg=${arg#.}
	fi

	# a version number?
	if [[ ${arg} != *.ebuild ]]; then
		arg=${reference%-*}-${arg}.ebuild
	fi

	echo "${arg}"
}

from='*.ebuild'
to=+1
case ${#} in
	0)
		;;
	1)
		to=${1}
		;;
	2)
		from=${1}
		to=${2}
		;;
	*)
		echo "Usage: pkgbump [<from> [<to>]]" >&2
		exit 1
		;;
esac

from=$(from_arg_to_filename "${from}")
check_valid "${from}"
to=$(version_arg_to_filename "${to}" "${from}")
check_valid "${to}"

set -e -x

scriptdir=${BASH_SOURCE%/*}
cp "${from}" "${to}"
"${scriptdir}"/copybump "${to}"
ekeyword ~all "${to}"
if grep -q "^PYTHON_COMPAT" "${to}" && type -P gpy-impl &>/dev/null; then
	gpy-impl "${to}" -@dead || :
fi
# tell ebuilds we don't want everything
export PKGBUMPING=${version}
GENTOO_MIRRORS= ebuild "${to}" manifest
[[ ! -f Manifest ]] || git add Manifest
git add "${to}"
echo "${version}" > .pkgbump-pv
exec "${scriptdir}"/pkgdiff-mg "${from}" "${to}"
