#!/bin/bash
#
# (c) 2026 Timothy Pearson <tpearson@debian.org>
# Licensed under the terms of the GNU General Public License v3
#
# This script regenerates 0002-regenerate-xnn-buildgn.patch
#
# Requires Bazel 8 (cannot be 9+) preinstalled on the host

set -ex

test -f chrome/BUILD.gn

rm -rf third_party/xnnpack.tmp
cp -a  third_party/xnnpack third_party/xnnpack.tmp

patch -d third_party/xnnpack.tmp -p3 < debian/patches/ppc64le/third_party/0001-add-xnn-ppc64el-support.patch
patch -d third_party/xnnpack.tmp -p3 < debian/patches/ppc64le/regen/xnnpack_local_regen_hacks.patch

(cd third_party/xnnpack.tmp && python3 generate_build_gn.py)

gn format third_party/xnnpack.tmp/BUILD.gn

cat > third_party/xnnpack.tmp/patch.new << END
File regenerated by running the 'regenerate_xnnpack_patch' script
Requires Bazel 8 (cannot be 9+) to regenerate

NOTE: Multiple Bazel 8 files have a "cpu:ppc" bug, where it should read "cpu:ppc64le"
This causes various toolchain failures of the form:

While resolving toolchains for target @@rules_python+//python:current_py_toolchain
	@@bazel_tools//tools/python:toolchain_type

This requires a one-time edit of two files in the Bazel cache directory to resolve:
	external/rules_python+/python/versions.bzl
	external/rules_python++python+pythons_hub/BUILD.bazel

END

! git diff --no-index --minimal \
	third_party/xnnpack/BUILD.gn \
	third_party/xnnpack.tmp/BUILD.gn \
>> third_party/xnnpack.tmp/patch.new

sed -ri 's!/(third_party/xnnpack)\.tmp/!/\1/!' third_party/xnnpack.tmp/patch.new

cp -f third_party/xnnpack.tmp/patch.new debian/patches/ppc64le/third_party/0002-regenerate-xnn-buildgn.patch

rm -r third_party/xnnpack.tmp
