#!/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 1 ]]; then
  log_fatal "Usage: $0 <BUILD_COMMAND>"
fi

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

# 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="cd /host; mkdir -p $BUILDDIR; cp -f /usr/bin/osbuild $BUILDDIR/osbuild; chcon system_u:object_r:install_exec_t:s0 $BUILDDIR/osbuild; export PATH=$BUILDDIR:\$PATH; export OSBUILD_BUILDDIR=$BUILDDIR; automotive-image-builder ${BUILD_COMMAND}"

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