#!/usr/bin/env bash
# [MISE] description="Assemble manifests into a single deploy.yaml for for kubectl apply"
# [MISE] tools={"pipx:jinja2-cli"="latest"}
# [MISE] outputs=["deploy.yaml"]
# [USAGE] arg "[image]" help="Override the image created. default=ttl.sh/mortenlj-$(basename \"${MISE_PROJECT_ROOT}\")"

set -o errexit
set -o pipefail

IMAGE="${usage_image:-ttl.sh/mortenlj-$(basename "${MISE_PROJECT_ROOT}")}"
VERSION="${MORTENLJ_MISE_LIB_CLEAN_VERSION:-1h}"

export IMAGE
export VERSION

output=$(mktemp deploy-XXXXXX --suffix=".yaml")

# Save current nullglob state as a command
NULLGLOB_OLD=$(shopt -p nullglob || true)
shopt -s nullglob

echo Assembling templates
for template in "${MISE_CONFIG_ROOT}/deploy/"*.j2; do
  echo ... "${template}"
  jinja2 "${template}" >> "${output?}"
done

echo Assembling plain files
for plain in "${MISE_CONFIG_ROOT}/deploy/"*.yaml; do
  echo ... "${plain}"
  cat "${plain}" >> "${output?}"
done

# Restore previous nullglob state
if [[ -n "$NULLGLOB_OLD" ]]; then
  eval "$NULLGLOB_OLD"
fi

output_directory="${MISE_CONFIG_ROOT}/mise-output"
mkdir --parents "${output_directory}"

mv "${output}" "${output_directory}/deploy.yaml"

echo "Manifests assembled at ${output_directory}/deploy.yaml"
