#!/usr/bin/env bash
set -euo pipefail

root="$(git rev-parse --show-toplevel)"
submodule="$root/third_party/n3n"
patch="$root/patches/n3n/embedded-mobile-integration.patch"
expected="43b62ac440646c2a5071ede5c671888c0c957236"
actual="$(git -C "$submodule" rev-parse HEAD)"

if [[ "$actual" != "$expected" ]]; then
	echo >&2 "Unexpected n3n revision: $actual (expected $expected)"
	exit 1
fi

if git -C "$submodule" apply --check --reverse "$patch" >/dev/null 2>&1; then
	echo "n3n patch already applied: $patch"
	exit 0
fi

if [[ -n "$(git -C "$submodule" status --short --untracked-files=no)" ]]; then
	echo >&2 "Cannot apply approved n3n patch: submodule has other tracked modifications."
	git -C "$submodule" status --short --untracked-files=no >&2
	exit 1
fi

git -C "$submodule" apply "$patch"
echo "n3n patch applied: $patch"
