#!/bin/bash
set -euo pipefail

# Source logging functions first
source lib/logging.sh

# Initialize debug mode (controlled by DEBUG environment variable)
init_debug_mode

# Check if at least one input argument is provided
if [[ "${#}" -lt 2 ]]; then
  log_fatal "Usage: $0 <AIB> <BUILD_COMMAND>"
fi

# Store the first input argument as BUILD_COMMAND
AIB="${1}"
BUILD_COMMAND="${2}"

# Check if BUILD_COMMAND is set
if [[ -z "${BUILD_COMMAND}" ]]; then
  log_fatal "BUILD_COMMAND is not set. Please check lib/create-osbuild.sh"
fi

LOCAL_CONTAINER_IMAGE="localhost/builder:latest"
BUILDDIR=_build
EXEC="mkdir -p /run/aib; mount -t tmpfs none /run/aib; cp -f /usr/bin/osbuild /run/aib/osbuild; chcon system_u:object_r:install_exec_t:s0 /run/aib/osbuild; export PATH=/run/aib:\$PATH; export OSBUILD_BUILDDIR=$BUILDDIR; ${AIB} ${BUILD_COMMAND}"

# Run the AIB container with the BUILD_COMMAND
podman run -i \
          -v /dev:/dev \
          -v "$PWD":/host \
          -v /var/lib/containers/storage:/var/lib/containers/storage:Z \
          -w /host \
          --rm \
          --privileged \
          $LOCAL_CONTAINER_IMAGE \
          /bin/bash -c "$EXEC"
