#!/bin/bash

## Copyright (C) 2025 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

## Runs inside the build container: executes the given command ("$@") from the
## source directory, tees its combined stdout/stderr to logs/build.log, and exits
## with the command's status (warning if the log write fails).

set -x
set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit
shopt -s shift_verbose
export LC_ALL=C

SOURCE_DIR="${HOME}/derivative-maker"
BINARY_DIR="${HOME}/derivative-binary"
LOG_DIR="${BINARY_DIR}/logs"
BUILD_LOG="${LOG_DIR}/build.log"

mkdir --parents -- "${BINARY_DIR}" "${LOG_DIR}"

chown --recursive -- "${USER}:${USER}" "${LOG_DIR}"

cd -- "${SOURCE_DIR}"

## Exit with the exit code of "$@", but print a warning if 'tee' fails.
declare -a pipe_status=( 0 0 )
"$@" 2>&1 | tee -a -- "${BUILD_LOG}" || pipe_status=( "${PIPESTATUS[@]}" )

if [ ! "${pipe_status[1]}" = "0" ]; then
   printf '%s\n' "${0##*/}: WARNING: writing '${BUILD_LOG}' failed (tee exit ${pipe_status[1]}); the on-disk build log is INCOMPLETE (out of disk?). The build itself exited ${pipe_status[0]}." >&2
fi

exit "${pipe_status[0]}"
