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

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

# go.work is the owner of the code-bearing L0 module set. Load every module and
# its own tests with workspace replacement disabled so a stale direct/indirect
# requirement cannot be masked until a late TiDB integration step.
modules=$(awk '
  /^use \(/ { in_use=1; next }
  in_use && /^\)/ { in_use=0; next }
  in_use && $1 ~ /^\.\// { print $1 }
' "$root/go.work")

if [[ -z "$modules" ]]; then
  echo "workspace module graph seal: go.work contains no modules" >&2
  exit 1
fi

for module in $modules; do
  (
    cd "$root/${module#./}"
    GOWORK=off go list -mod=readonly -deps -test ./... >/dev/null
  )
done

# Both production image builds compile commands from backend/go.mod. Every
# platform-owned local replacement therefore belongs to each Docker build
# context even when a particular command does not currently import it: Go may
# inspect replacement module metadata while resolving the main module graph.
# Keep this derived from backend/go.mod so adding a sibling module cannot leave
# the checked-in image closure stale until the expensive Docker job.
local_replace_dirs=$(cd "$root/backend" && go mod edit -json | jq -r '
  .Replace[]
  | select(.New.Path | startswith("../"))
  | .New.Path
  | sub("^\\.\\./"; "")
' | sort -u)

for dockerfile in infra/runtime.Dockerfile; do
  dockerignore="$root/${dockerfile}.dockerignore"
  for module_dir in $local_replace_dirs; do
    if ! grep -Eq "^COPY[[:space:]].*${module_dir}/go\\.mod([[:space:]]|$)" "$root/$dockerfile"; then
      echo "workspace module graph seal: $dockerfile omits $module_dir/go.mod required by backend/go.mod" >&2
      exit 1
    fi
    if ! grep -Eq "^COPY[[:space:]].*${module_dir}/[[:space:]]" "$root/$dockerfile"; then
      echo "workspace module graph seal: $dockerfile omits $module_dir source required by backend/go.mod" >&2
      exit 1
    fi
    if [[ -f "$dockerignore" ]] && \
       { ! grep -Fxq "!${module_dir}/" "$dockerignore" || \
         ! grep -Fxq "!${module_dir}/**" "$dockerignore"; }; then
      echo "workspace module graph seal: ${dockerfile}.dockerignore excludes $module_dir required by backend/go.mod" >&2
      exit 1
    fi
  done
done

echo "workspace module graph seal: OK"
