#!/bin/sh
# Rebuild the extracted Tempo datasource ($1) against official Tempo v3.1.0.
# The tag's go.mod says "module github.com/grafana/tempo", which Go rejects for
# a v3 version, so the tag is served as github.com/grafana/tempo/v3 from a file
# proxy. There is no replace directive. The caller must keep
# GOPROXY=https://proxy.golang.org,file:///tmp/tempo-modproxy and
# GONOSUMDB=github.com/grafana/tempo/v3 for the following go commands.
set -eu
if [ "$#" -ne 1 ] || [ ! -d "$1" ]; then
  echo 'usage: pin-tempo-v3.sh <datasource-dir>' >&2
  exit 2
fi
ds=$1
sha=69302279a96cf7a58f19ed910f2e782b6b87aba7577ab02c93130e2764ebd211
tarball=/tmp/tempo-v3.1.0.tar.gz
proxy=/tmp/tempo-modproxy/github.com/grafana/tempo/v3/@v
apk add --no-cache python3 >/dev/null
if [ ! -f "$tarball" ]; then
  wget -q -O "$tarball" https://codeload.github.com/grafana/tempo/tar.gz/refs/tags/v3.1.0
fi
printf '%s  %s\n' "$sha" "$tarball" | sha256sum -c -
rm -rf /tmp/tempo-3.1.0 /tmp/tempo-modproxy
tar -C /tmp -xzf "$tarball"
mkdir -p "$proxy"
python3 - "$ds" <<'PY'
import pathlib, re, sys, zipfile
ds = pathlib.Path(sys.argv[1])
root = pathlib.Path("/tmp/tempo-3.1.0")
pat = re.compile(r"github.com/grafana/tempo(?!/v3)")
def rewrite(path):
    text = path.read_text(errors="replace")
    new = pat.sub("github.com/grafana/tempo/v3", text)
    if new != text:
        path.write_text(new)
        return 1
    return 0
n = 0
for path in root.rglob("*"):
    if path.is_file() and path.suffix in {".go", ".mod"}:
        n += rewrite(path)
print(f"rewrote {n} Tempo files")
print(root.joinpath("go.mod").read_text().splitlines()[0])
nested = [path.parent for path in root.rglob("go.mod") if path.parent != root]
prefix = "github.com/grafana/tempo/v3@v3.1.0/"
zpath = pathlib.Path("/tmp/tempo-modproxy/github.com/grafana/tempo/v3/@v/v3.1.0.zip")
with zipfile.ZipFile(zpath, "w", compression=zipfile.ZIP_DEFLATED) as zf:
    for path in root.rglob("*"):
        if not path.is_file():
            continue
        if any(module == path or module in path.parents for module in nested):
            continue
        zf.write(path, prefix + str(path.relative_to(root)))
print(f"zip {zpath.stat().st_size} excluding {len(nested)} nested modules")
dn = 0
for path in ds.rglob("*.go"):
    dn += rewrite(path)
print(f"rewrote {dn} datasource files")
PY
cp /tmp/tempo-3.1.0/go.mod "$proxy/v3.1.0.mod"
printf '%s\n' '{"Version":"v3.1.0","Time":"2026-09-29T17:06:39Z"}' > "$proxy/v3.1.0.info"
printf '%s\n' v3.1.0 > "$proxy/list"
cd "$ds"
go mod edit -droprequire=github.com/grafana/tempo
go mod edit -require=github.com/grafana/tempo/v3@v3.1.0
