#!/bin/bash

# Copyright (c) 2026 Tigera, Inc. All rights reserved.

# codegen.sh runs inside the go-build container and generates all of the Go
# artifacts for the API package: defaults, deep copies, OpenAPI definitions,
# and the clientset/listers/informers. CRD generation stays in the Makefile
# because it relies on the in-repo Calico-patched controller-gen, which only
# exists in the calico monorepo.
#
# This script is mirrored into the standalone projectcalico/api and tigera/api
# repos, so keep it free of monorepo-only assumptions and drive everything off
# PACKAGE_NAME.

set -eo pipefail

: "${PACKAGE_NAME:?PACKAGE_NAME must be set}"

REPO_ROOT="/go/src/${PACKAGE_NAME}"
HEADER="${REPO_ROOT}/hack/boilerplate/boilerplate.go.txt"

###############################################################################
# Defaults and deep copies
###############################################################################
defaulter-gen \
	--v 1 --logtostderr \
	--go-header-file "${HEADER}" \
	--extra-peer-dirs "${PACKAGE_NAME}/pkg/apis/projectcalico/v3" \
	--output-file zz_generated.defaults.go \
	"${PACKAGE_NAME}/pkg/apis/projectcalico/v3"

deepcopy-gen \
	--v 1 --logtostderr \
	--go-header-file "${HEADER}" \
	--output-file zz_generated.deepcopy.go \
	"${PACKAGE_NAME}/pkg/apis/projectcalico/v3"

###############################################################################
# OpenAPI
###############################################################################
# Generate OpenAPI model name accessors for Calico types. These implement the
# OpenAPIModelNamer interface so the apiserver's OpenAPI spec uses REST-friendly
# definition names (dots) instead of raw Go package paths (slashes). The
# definition output goes to /tmp since we only need the model name files; the
# real definitions are generated by the next step with all input packages.
openapi-gen \
	--v 1 --logtostderr \
	--go-header-file "${HEADER}" \
	--output-dir /tmp/openapi-gen-model-names \
	--output-pkg "${PACKAGE_NAME}/pkg/openapi" \
	--output-model-name-file zz_generated.model_name.go \
	"${PACKAGE_NAME}/pkg/apis/projectcalico/v3" \
	"${PACKAGE_NAME}/pkg/lib/numorstring"

# Generate the OpenAPI definitions. Must run before client-gen, which uses the
# output for --openapi-schema. Fail on any new API rule violations in Calico
# types (upstream k8s violations are ignored via the known-violations list).
openapi-gen \
	--v 1 --logtostderr \
	--go-header-file "${HEADER}" \
	--output-dir "${REPO_ROOT}/pkg/openapi" \
	--output-pkg "${PACKAGE_NAME}/pkg/openapi" \
	"${PACKAGE_NAME}/pkg/apis/projectcalico/v3" \
	"k8s.io/api/core/v1" \
	"k8s.io/api/networking/v1" \
	"k8s.io/apimachinery/pkg/apis/meta/v1" \
	"k8s.io/apimachinery/pkg/runtime" \
	"k8s.io/apimachinery/pkg/util/intstr" \
	"k8s.io/apimachinery/pkg/version" \
	"${PACKAGE_NAME}/pkg/lib/numorstring" 2>&1 | tee /tmp/openapi-gen.log
grep "API rule violation" /tmp/openapi-gen.log | grep "projectcalico" > /tmp/openapi-violations.log || true
if [ -s /tmp/openapi-violations.log ]; then
	# Strip comments and blank lines before using the known list as a pattern
	# file. A blank line makes grep -F match everything, which silently disables
	# the gate.
	KNOWN_VIOLATIONS=$(mktemp)
	grep -v -e '^#' -e '^[[:space:]]*$' "${REPO_ROOT}/hack/openapi-violations-known.list" > "${KNOWN_VIOLATIONS}" || true
	grep -v -x -F -f "${KNOWN_VIOLATIONS}" /tmp/openapi-violations.log > /tmp/openapi-new-violations.log || true
	rm -f "${KNOWN_VIOLATIONS}"
	if [ -s /tmp/openapi-new-violations.log ]; then
		echo "ERROR: openapi-gen reported new API rule violations in Calico types:"
		cat /tmp/openapi-new-violations.log
		echo "If these are intentional, add them to hack/openapi-violations-known.list"
		exit 1
	fi
fi

###############################################################################
# Clientset, listers, and informers
###############################################################################
APPLY_CONFIG_PKG="${PACKAGE_NAME}/pkg/client/applyconfiguration_generated"
APPLY_CONFIG_DIR="${REPO_ROOT}/pkg/client/applyconfiguration_generated"

# Generate the OpenAPI schema JSON for applyconfiguration-gen. This populates
# the structured-merge-diff type information in internal/internal.go, which is
# required for fake.NewClientset() to work correctly.
OPENAPI_SCHEMA=$(mktemp)
trap 'rm -f "${OPENAPI_SCHEMA}"' EXIT
echo "Generating OpenAPI schema for applyconfiguration-gen..."
go run "${REPO_ROOT}/hack/openapi-schema/" > "${OPENAPI_SCHEMA}"

# Generate apply configurations (required for NewClientset in the fake clientset).
applyconfiguration-gen \
	--go-header-file "${HEADER}" \
	--openapi-schema "${OPENAPI_SCHEMA}" \
	--output-dir "${APPLY_CONFIG_DIR}" \
	--output-pkg "${APPLY_CONFIG_PKG}" \
	"${PACKAGE_NAME}/pkg/apis/projectcalico/v3"

# Patch applyconfiguration-gen bugs (see patches/0002-* and patches/0003-*).
patch -p2 -d "${REPO_ROOT}" < "${REPO_ROOT}/patches/0002-Fix-duplicate-ensureProtoPort-method-in-FelixConfigurationSpec.patch"
patch -p2 -d "${REPO_ROOT}" < "${REPO_ROOT}/patches/0003-Fix-pointer-slice-append-in-IPAMBlockSpec-Allocations.patch"

# Generate the versioned clientset (pkg/client/clientset_generated/clientset).
client-gen \
	--go-header-file "${HEADER}" \
	--input-base "${PACKAGE_NAME}/pkg/apis/" \
	--input "projectcalico/v3" \
	--output-dir "${REPO_ROOT}/pkg/client/clientset_generated" \
	--clientset-path "${PACKAGE_NAME}/pkg/client/clientset_generated/" \
	--clientset-name "clientset" \
	--apply-configuration-package "${APPLY_CONFIG_PKG}"

# Generate listers.
lister-gen \
	--go-header-file "${HEADER}" \
	--output-dir "${REPO_ROOT}/pkg/client/listers_generated" \
	--output-pkg "${PACKAGE_NAME}/pkg/client/listers_generated" \
	"${PACKAGE_NAME}/pkg/apis/projectcalico/v3"

# Generate informers.
informer-gen \
	--go-header-file "${HEADER}" \
	--versioned-clientset-package "${PACKAGE_NAME}/pkg/client/clientset_generated/clientset" \
	--listers-package "${PACKAGE_NAME}/pkg/client/listers_generated" \
	--output-dir "${REPO_ROOT}/pkg/client/informers_generated" \
	--output-pkg "${PACKAGE_NAME}/pkg/client/informers_generated" \
	"${PACKAGE_NAME}/pkg/apis/projectcalico/v3"

# Patch the informer-gen bug (see patches/0004-*): the WithInformerName(gvr)
# resource name is built with a naive plural that doesn't match the real API
# plural for 7 v3 types. Will fail loudly once upstream is fixed and the patch
# becomes a no-op.
patch -p2 -d "${REPO_ROOT}" < "${REPO_ROOT}/patches/0004-Fix-informer-GVR-plural-strings.patch"
