#!/usr/bin/env bash

# This script is meant to be ran by "go generate". To run it directly, paths need to be adjusted

set -euo pipefail

original_pwd=$(pwd)

# TODO(lcaparelli): only fetch CRDs if the resulting map is not up-to-date already. Maybe we could store last fetched tag, and only pull if a newer tag exists.

# Create a temporary directory
TEMP_DIR=$(mktemp -d)

# https://askubuntu.com/a/1074185
git clone -n --depth=1 --filter=tree:0 https://github.com/crossplane-contrib/provider-upjet-aws.git "${TEMP_DIR}"
cd "$TEMP_DIR"
git sparse-checkout set --no-cone /package/crds/
git checkout

# Iterate over files in package/crds and apply a yq expression
for FILE in package/crds/*; do
  # For some reason the string interpolation runs even if the result from select is empty, causing it to output "." for CRDs without tags.
  # We use grep to work around it. Since the grep may fail and return 1, we combine it with " || true" to make the expression return 0.
  yq eval \
  'select(.spec.versions[].schema.openAPIV3Schema.properties.spec.properties.forProvider.properties.tags != null) | "\(.spec.names.singular).\(.spec.group)"' \
  "$FILE" | (grep -Ev "^\.$" || true) >> taggableGroupKinds.txt
done

cd $original_pwd

# Generate a valid Go file from the contents of taggableGroupKinds.txt
GO_FILE="zz_taggable.go"

echo '//go:generate ../hack/generate_taggable_filter.sh' > "$GO_FILE"
echo '// this file has been autogenerated by "go generate". Do not edit it manually' >> "$GO_FILE"
echo 'package internal' >> "$GO_FILE"
echo '' >> "$GO_FILE"
echo 'var taggableGroupKinds = map[string]bool{' >> "$GO_FILE"

while IFS= read -r group_kind || [ -n "$group_kind" ]; do
  echo "	\"$group_kind\": true," >> "$GO_FILE"
done < "$TEMP_DIR/taggableGroupKinds.txt"

echo '}' >> "$GO_FILE"

echo "Generated $GO_FILE containing taggable group versions."
