#!/bin/bash
# Configure rootfs type for bootc installation
set -xeuo pipefail

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

# Support overriding the rootfs at build time
CONFIG_DIR="/usr/lib/bootc/install"
mkdir -p "${CONFIG_DIR}"

# Do we have an explicit build-time override? Then write it.
if [ -n "$ROOTFS" ]; then
  cat > "${CONFIG_DIR}/80-rootfs-override.toml" <<EOF
[install.filesystem.root]
type = "$ROOTFS"
EOF
else
  # Query the default rootfs
  base_rootfs=$(bootc install print-configuration | jq -r '.filesystem.root.type // ""')

  # No filesystem override set. If we're doing composefs, we need a FS that
  # supports fsverity. If btrfs is available we'll pick that, otherwise ext4.
  fs=
  case "${VARIANT}" in
    composefs*)
      btrfs=$(grep -qEe '^CONFIG_BTRFS_FS' /usr/lib/modules/*/config && echo btrfs || true)
      fs=${btrfs:-ext4}
      ;;
    *)
      # No explicit filesystem set and we're not using composefs. Default to xfs
      # with the rationale that we're trying to get filesystem coverage across
      # all the cases in general.
      if [ -z "${base_rootfs}" ]; then
        fs=xfs
      fi
      ;;
  esac

  if [ -n "$fs" ]; then
    cat > "${CONFIG_DIR}/80-ext4-composefs.toml" <<EOF
[install.filesystem.root]
type = "${fs}"
EOF
  fi
fi
