#!/bin/bash set -euo pipefail # Function to log messages with timestamp log() { echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*" >&2 } # Function to handle cleanup on exit cleanup() { local exit_code=$? if [ $exit_code -ne 0 ]; then log "Build process exited with code: $exit_code" # Optional: Save ccache stats on failure if command -v ccache >/dev/null 2>&1; then log "Final ccache stats:" ccache -s fi fi } # Set up signal handlers trap cleanup EXIT trap 'log "Received SIGTERM, shutting down gracefully..."; exit 143' TERM trap 'log "Received SIGINT, shutting down gracefully..."; exit 130' INT # Initialize environment log "Initializing build environment for user: $(whoami)" # Ensure proper ownership of workspace if [ -d "/workspace" ] && [ -w "/workspace" ]; then log "Workspace permissions verified" else log "Warning: Workspace permissions may be incorrect" fi # Display ccache status if command -v ccache >/dev/null 2>&1; then log "ccache status:" ccache -s fi # Display system info for debugging log "System info - Cores: $(nproc), Memory: $(free -h | awk '/^Mem:/ {print $2}')" # Set optimal make flags if not already set if [ -z "${MAKEFLAGS:-}" ]; then export MAKEFLAGS="-j$(nproc)" log "Set MAKEFLAGS to: $MAKEFLAGS" fi # If no arguments provided, start interactive bash if [ $# -eq 0 ]; then log "Starting interactive bash session" exec /bin/bash fi # Define log file path BUILD_LOG="/workspace/build.log" # Clean previous logs : > "$BUILD_LOG" # This truncates the file without deleting it # Or, alternatively: rm -f "$BUILD_LOG" && touch "$BUILD_LOG" log "Executing command: $*" # Run command, tee stdout/stderr to build.log and still display in docker logs "$@" > >(tee -a "$BUILD_LOG") 2> >(tee -a "$BUILD_LOG" >&2) exit_code=$? log "Command exited with code $exit_code" exit $exit_code