#!/bin/bash
# Inject base configuration files for CI testing of transient-root/etc/var configurations.
# Arguments: $1=variant, $2=baseconfigs (comma-separated, may be empty)
set -xeuo pipefail

VARIANT="${1:-}"
BASECONFIGS="${2:-}"

# No-op if no baseconfigs specified
if [ -z "${BASECONFIGS}" ]; then
  exit 0
fi

# setup-root-conf.toml is composefs-specific; ostree uses prepare-root.conf
# which has a different (INI) format and different option names.
case "${VARIANT}" in
  composefs*)
    TARGET="/usr/lib/composefs/setup-root-conf.toml"
    ;;
  *)
    echo "inject-baseconfig: baseconfigs not supported for variant '${VARIANT}'" >&2
    exit 1
    ;;
esac

mkdir -p "$(dirname "${TARGET}")"

# Split on commas and process each token
IFS=',' read -ra TOKENS <<< "${BASECONFIGS}"
for raw_token in "${TOKENS[@]}"; do
  # Trim leading/trailing spaces
  token="${raw_token#"${raw_token%%[![:space:]]*}"}"
  token="${token%"${token##*[![:space:]]}"}"

  [ -z "${token}" ] && continue

  case "${token}" in
    etc-transient)
      printf '[etc]\ntransient = true\n' >> "${TARGET}"
      ;;
    root-transient)
      printf '[root]\ntransient = true\n' >> "${TARGET}"
      ;;
    var-volatile)
      # Mount /var as a fresh tmpfs on every boot via systemd.volatile=state.
      # bootc-root-setup detects this karg in the initramfs and automatically
      # skips the /var state bind-mount, leaving /var as an empty directory
      # from the composefs image.  systemd-fstab-generator then mounts a fresh
      # tmpfs there at local-fs.target.  Using a plain tmpfs avoids the
      # overlayfs-on-overlayfs restriction that breaks tools like podman which
      # use overlayfs under /var/lib/containers.
      mkdir -p /usr/lib/bootc/kargs.d
      printf 'kargs = ["systemd.volatile=state"]\n' \
        > /usr/lib/bootc/kargs.d/50-var-volatile.toml
      ;;
    *)
      echo "Unknown baseconfig: ${token}" >&2
      exit 1
      ;;
  esac
done
