c_josie_overlay

#!/usr/bin/env bash
# Mechanical version bumps for josie-overlay packages.
#
#   scripts/overlay-bump.sh [<cat/pkg> ...]
#
# No args: bump everything scripts/overlay-sweep.sh reports BEHIND. With args:
# only those packages (a package the sweep calls `ok` is skipped). One version
# per directory: this overlay tracks upstream, so a bump is a rename, not an
# addition. Per package the script:
#
#   1. git-mv <pn>-<old>.ebuild -> <pn>-<new>.ebuild
#   2. git-mv files/<pn>-<old>-* patches -> <pn>-<new>-* and rewrite the
#      ${PN}-<old>- / <pn>-<old>- references in the ebuild
#   3. regenerate the Manifest (`ebuild <new> manifest`; distfiles are cached
#      under /tmp/opencode/distdir so the real DISTDIR stays untouched)
#   4. if patches were renamed: unpack the fetched distfile and dry-run every
#      patch against the *new* source. Drift (or an upstream fix making the
#      patch obsolete) => roll the package back to HEAD and report NEEDS-REVIEW.
#   5. per-package extra checks (see EXTRA): opencode-bin verifies the
#      downloaded tarballs against the npm registry's sha512 integrity.
#
# Deterministic and safe to re-run; anything it cannot do cleanly is left at
# HEAD and named in the summary. After a green run: scripts/overlay-gate.sh
# <cat/pkg>..., then commit. The ROCm chain is deliberately NOT scriptable
# (7 interlocking packages + per-release source porting) — bump it by hand.
set -euo pipefail

root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
cd "$root"

work=/tmp/opencode
distdir=$work/distdir
mkdir -p "$distdir" "$work/portage"
export DISTDIR=$distdir PORTAGE_TMPDIR=$work/portage TMPDIR=$work HOME=$work

# BEHIND rows from the sweep: "label old new" per line (filtered by $@ if given)
labels=""
sweep=$(./scripts/overlay-sweep.sh)
echo "$sweep"
while read -r label old new mark; do
	[ "$mark" = BEHIND ] || continue
	if [ $# -gt 0 ]; then
		take=0
		for want in "$@"; do [ "$want" = "$label" ] && take=1; done
		[ $take -eq 1 ] || continue
	fi
	labels+="$label $old $new"$'\n'
done <<<"$sweep"

[ -n "$labels" ] || { echo; echo "nothing to bump."; exit 0; }

# labels that are not single package directories
manual() { case $1 in rocm-therock-chain) return 0;; *) return 1;; esac; }
# label -> extra check function (after Manifest regen, before accepting)
declare -A EXTRA=([dev-util/opencode-bin]=extra_opencode_bin)

extra_opencode_bin() { # <new> — npm sha512 integrity vs the fetched tarballs
	local pair npmarch distname want got
	local dir=dev-util/opencode-bin
	for pair in amd64:x64 arm64:arm64; do
		npmarch=${pair##*:}
		distname="opencode-bin-$1-${pair%%:*}.tgz"
		[ -f "$distdir/$distname" ] || { echo "FAIL: $distname was not fetched"; return 1; }
		want=$(curl -fsSL "https://registry.npmjs.org/@opencode/cli-linux-$npmarch/$1" \
			| python3 -c 'import sys,json;print(json.load(sys.stdin)["dist"]["integrity"])')
		got=$(python3 -c 'import sys,hashlib,base64;print("sha512-"+base64.b64encode(hashlib.file_digest(open(sys.argv[1],"rb"),"sha512").digest()).decode())' "$distdir/$distname")
		if [ "$want" != "$got" ]; then
			echo "FAIL: npm integrity mismatch for $distname"
			echo "  registry: $want"
			echo "  computed: $got"
			return 1
		fi
		echo "PASS: npm sha512 integrity $distname"
	done
}

verify_patches() { # <dir> <pn> <new> — rc 0 clean, 1 drift, 2 cannot verify
	local dir=$1 pn=$2 new=$3 fname top p rc=0 ndist src
	ndist=$(awk '$1=="DIST"{n++} END{print n+0}' "$dir/Manifest")
	if [ "$ndist" -ne 1 ]; then
		echo "WARN: $ndist distfiles in Manifest; cannot auto-locate the source tree"
		return 2
	fi
	fname=$(awk '$1=="DIST"{print $2}' "$dir/Manifest")
	if [ ! -f "$distdir/$fname" ]; then
		echo "WARN: $fname missing from $distdir"
		return 2
	fi
	src=$(mktemp -d "$work/unpack.XXXXXX")
	case $fname in
		*.tar.gz|*.tgz) tar -xzf "$distdir/$fname" -C "$src" ;;
		*.zip)          unzip -q "$distdir/$fname" -d "$src" ;;
		*) rm -rf "$src"; echo "WARN: unhandled distfile type: $fname"; return 2 ;;
	esac
	# archives unpack to one top dir (that is ${WORKDIR}/<dir> == S); else root
	if [ -d "$src/$pn" ]; then top=$src/$pn
	else top=$src
	fi
	for p in "$dir"/files/"$pn"-"$new"-*; do
		[ -e "$p" ] || continue
		if patch -d "$top" -p1 -F0 -N -t --dry-run <"$p" >/dev/null; then
			echo "PASS: patch dry-run $(basename "$p")"
		else
			echo "FAIL: $(basename "$p") does not apply cleanly to $new source"
			rc=1
		fi
	done
	rm -rf "$src"
	return $rc
}

rollback() { # <dir> — undo everything git-tracked under the package dir
	git restore --source=HEAD --staged --worktree -- "$1"
	git clean -fdq -- "$1"
}

bumped=() failed=() skipped=()
while read -r label old new; do
	[ -n "$label" ] || continue
	if manual "$label"; then
		echo; echo "== $label $old -> $new: NOT SCRIPTABLE, bump by hand =="
		skipped+=("$label")
		continue
	fi
	dir=$label pn=${label##*/}
	echo; echo "== bump $label $old -> $new =="
	if ! git mv "$dir/$pn-$old.ebuild" "$dir/$pn-$new.ebuild"; then
		failed+=("$label (ebuild rename)"); continue
	fi
	renamed_patches=0
	if [ -d "$dir/files" ]; then
		for f in "$dir"/files/"$pn"-"$old"-*; do
			[ -e "$f" ] || continue
			if git mv "$f" "$dir/files/$pn-$new-${f##*/$pn-$old-}"; then
				renamed_patches=1
			fi
		done
		if [ $renamed_patches -eq 1 ]; then
			# the ebuild references the patch two ways: literal "${PN}-<old>-"
			# (unexpanded file text) or "<pn>-<old>-"
			sed -i -e "s|\${PN}-$old-|\${PN}-$new-|g" -e "s|$pn-$old-|$pn-$new-|g" "$dir/$pn-$new.ebuild"
		fi
	fi
	if ! ebuild "$dir/$pn-$new.ebuild" manifest; then
		rollback "$dir"; echo "FAIL: Manifest regeneration"; failed+=("$label (manifest)"); continue
	fi
	if [ $renamed_patches -eq 1 ]; then
		rc=0; verify_patches "$dir" "$pn" "$new" || rc=$?
		if [ $rc -eq 1 ]; then
			rollback "$dir"
			echo "NEEDS-REVIEW: rolled back — re-derive the patch against $new, or drop it if upstream fixed the bug"
			failed+=("$label (patch drift)"); continue
		elif [ $rc -eq 2 ]; then
			echo "NEEDS-REVIEW: patch dry-run skipped — verify it manually before merging"
		fi
	fi
	if [ -n "${EXTRA[$label]:-}" ] && ! "${EXTRA[$label]}" "$new"; then
		rollback "$dir"
		echo "FAIL: extra check ${EXTRA[$label]} — rolled back"
		failed+=("$label (extra check)"); continue
	fi
	bumped+=("$label $old -> $new")
done <<<"$labels"

echo
echo "== summary =="
for b in "${bumped[@]:-}";  do [ -n "$b" ] && echo "BUMPED:        $b"; done
for s in "${skipped[@]:-}"; do [ -n "$s" ] && echo "NOT SCRIPTABLE: $s (manual bump)"; done
for f in "${failed[@]:-}";  do [ -n "$f" ] && echo "NEEDS-REVIEW:  $f"; done
[ ${#failed[@]} -eq 0 ] || exit 1

if [ ${#bumped[@]} -gt 0 ]; then
	echo
	echo "Next: ./scripts/overlay-gate.sh $(printf '%s ' "${bumped[@]%% *}")"
fi
exit 0