#!/usr/bin/env bash
set -e
set -x
# only exit with zero if all commands of the pipeline exit successfully
set -o pipefail

# Ensure that we use the binaries from the versions defined in hack/tools/go.mod.
PATH="$(pwd)/tmp/bin:${PATH}"

prefix="assets"
rm -rf $prefix || :
mkdir $prefix

TMP=$(mktemp -d -t tmp.XXXXXXXXXX)
echo "Created temporary directory at $TMP"

jsonnet -J jsonnet/vendor -J tmp/json-manifests jsonnet/main.jsonnet > "${TMP}/main.json"

# Replace mapfile with while loop so it works with previous bash versions (Mac included)
#mapfile -t files < <(jq -r 'keys[]' tmp/main.json)
while IFS= read -r line; do
	files+=("$line")
done < <(jq -r 'keys[]' "${TMP}/main.json")

maxProc=$(nproc || echo 4)

# process all files in parallel
for file in "${files[@]}"; do
	{
		dir=$(dirname "${file}")
		path="${prefix}/${dir}"
		mkdir -p "${path}"

		# convert file name from camelCase to snake-case
		fullfile=$(echo "${file}" | sed 's/\(.\)\([A-Z]\)/\1-\2/g' | tr '[:upper:]' '[:lower:]')
		jq -r ".[\"${file}\"]" "${TMP}/main.json" | gojsontoyaml > "${prefix}/${fullfile}.yaml"
	}&

	# wait for at least one of the jobs to finish if there are more than maxProc jobs
	while [[ $(jobs -r | wc -l ) -ge "$maxProc" ]]; do wait -n; done
done
# wait for all jobs to finish
wait


grep -H 'kind: CustomResourceDefinition' assets/{cluster-monitoring,prometheus}-operator/* | cut -d: -f1 | while IFS= read -r f; do
  mv "$f" "manifests/0000_50_cluster-monitoring-operator_00_$(basename "$f")"
done

# Move jsonnet generated ClusterRole and Role objects to the manifests/ directory.
mv "${prefix}/cluster-monitoring-operator/cluster-role.yaml" \
   "${prefix}/manifests/0000_50_cluster-monitoring-operator_02-role.yaml"
mv "${prefix}/cluster-monitoring-operator/namespaced-cluster-role.yaml" \
   "${prefix}/manifests/0000_50_cluster-monitoring-operator_02-namespaced-cluster-role.yaml"
mv "${prefix}/cluster-monitoring-operator/alert-customization-role.yaml" \
   "${prefix}/manifests/0000_50_cluster-monitoring-operator_02-alert-customization-role.yaml"

# Move resulting manifests to the manifests directory
mv assets/manifests/* manifests/
rmdir assets/manifests || true
