#!/bin/bash
set -euo pipefail

# Get script directory - handle different execution contexts
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
PROJECT="$(basename "${SCRIPT_DIR}")"

# Debug output for CI
echo "${PROJECT} build script running from: ${SCRIPT_DIR}"

# handle running locally, or docker in docker via gitea runner.
if [ -n "${GITEA_CONTAINER_NAME:-}" ]; then
  echo "We're in a gitea container: ${GITEA_CONTAINER_NAME}"
  VOLUME_OPTS=("--volumes-from=${GITEA_CONTAINER_NAME}")
  WORKING_DIR=("-w" "${GITHUB_WORKSPACE}/${PROJECT}")
  BUILD_DIR="${GITHUB_WORKSPACE}/${PROJECT}/build"
  OUTPUT_DIR="${GITHUB_WORKSPACE}/${PROJECT}/output"
else
  VOLUME_OPTS=("-v" "${SCRIPT_DIR}:/app")
  WORKING_DIR=("-w" "/app")
  BUILD_DIR="${SCRIPT_DIR}/build"
  OUTPUT_DIR="${SCRIPT_DIR}/output"
fi

# Create output directory
mkdir -p "${OUTPUT_DIR}"

# Run build in container with mounted directories
COMMAND_TO_RUN="cmake -G Ninja -S . -B ./build \
                -DCMAKE_BUILD_TYPE=\${CMAKE_BUILD_TYPE} \
                -DPROJECT_NAME=${PROJECT} && \
                cmake --build ./build" 

echo "Building in new docker container"
docker run --rm \
  --user "$(id -u):$(id -g)" \
  "${VOLUME_OPTS[@]}" \
  "${WORKING_DIR[@]}" \
  -e CMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE:-Debug}" \
  gitea.jde.nz/public/dropshell-build-base:latest \
  bash -c "${COMMAND_TO_RUN}"

# Copy built executable to output directory
if [ -f "${BUILD_DIR}/${PROJECT}" ]; then
  cp "${BUILD_DIR}/${PROJECT}" "${OUTPUT_DIR}/"
  echo "✓ Build successful - ${PROJECT} copied to ${OUTPUT_DIR}/"
else
  echo "✗ Build failed - ${PROJECT} not found in ${BUILD_DIR}/"
  exit 1
fi

echo "Build complete"
