#!/bin/bash
set -e

# Directory of this script
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
ROOT_DIR="${SCRIPT_DIR}/.."
CHART_PATH="${ROOT_DIR}/k8s/monitoring/charts/kube-prometheus-stack-75.12.0.tgz"
OUTPUT_FILE="${ROOT_DIR}/k8s/crds/all-crds.yaml"
TEMP_DIR=$(mktemp -d)

echo "Extracting CRDs from ${CHART_PATH}..."

# Extract the chart to a temporary directory
tar -xf "${CHART_PATH}" -C "${TEMP_DIR}"

# Concatenate all CRDs into the output file
echo "# Generated by scripts/update-crds.sh" > "${OUTPUT_FILE}"
echo "# Source: kube-prometheus-stack-75.12.0.tgz" >> "${OUTPUT_FILE}"

# The CRDs are located in kube-prometheus-stack/charts/crds/crds/
CRD_DIR="${TEMP_DIR}/kube-prometheus-stack/charts/crds/crds"

if [ ! -d "${CRD_DIR}" ]; then
  echo "Error: CRD directory not found at ${CRD_DIR}"
  rm -rf "${TEMP_DIR}"
  exit 1
fi

# Loop through yaml files and append them
for crd in "${CRD_DIR}"/*.yaml; do
  echo "---" >> "${OUTPUT_FILE}"
  cat "${crd}" >> "${OUTPUT_FILE}"
done

echo "CRDs updated in ${OUTPUT_FILE}"

# Cleanup
rm -rf "${TEMP_DIR}"
