#!/usr/bin/env bash

# Copyright 2025 The KCP Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -euo pipefail

cd $(dirname $0)/..
source hack/lib.sh

mkdir -p _tools
export GOBIN=$(realpath _tools)

go install k8c.io/reconciler/cmd/reconciler-gen
go install sigs.k8s.io/controller-tools/cmd/controller-gen

echodate "Generating reconciling helpers…"

reconcileHelpers=internal/resources/reconciling/zz_generated_reconcile.go
$GOBIN/reconciler-gen --config hack/reconciling.yaml > $reconcileHelpers

CRD_DIR=deploy/crd
KCP_CRD_DIR="$CRD_DIR/kcp.io"
rm -rf -- "$KCP_CRD_DIR"
mkdir -p "$KCP_CRD_DIR"

echodate "Generating openAPI v3 CRDs…"

$GOBIN/controller-gen \
  crd \
  paths=./sdk/apis/... \
  output:crd:dir=./$KCP_CRD_DIR

# these are types only used for testing the syncer
$GOBIN/controller-gen \
  crd \
  paths=./internal/sync/apis/... \
  output:crd:dir=./internal/sync/crd/

beautify() {
  _tools/yq --inplace --no-doc 'del(.metadata.creationTimestamp)' "$1"

  mv "$1" "$1.bak"
  echo -e "# This file has been generated by hack/update-codegen-crds.sh, DO NOT EDIT.\n" > "$1"
  cat "$1.bak" >> "$1"
  rm "$1.bak"
}

# beautify CRDs just because we can
for f in $KCP_CRD_DIR/*.yaml; do
  beautify "$f"
done

for f in internal/sync/crd/*.yaml; do
  beautify "$f"
done
