#!/bin/bash

# Build every target architecture, saving log files to build/log.
# If $FORK is set, build them in parallel.

source sources/utility_functions.sh || exit 1

test -z $CROSS_COMPILER_HOST && export CROSS_COMPILER_HOST=i686

trap "killtree $$" EXIT

# Build the host architecture.  This has to be built first so the other
# architectures can canadian cross static compilers to run on the host using
# this toolchain to link against a host version of uClibc.

# This also performs the download.sh and host-tools.sh steps, which don't
# parallelize well if many build.sh instances try to call them at once.

# If this fails, don't bother trying to build the other targets.

test -z $NO_CLEAN && blank_tempdir build

mkdir -p build/logs &&
shell {'EXTRACT_ALL=1' ./download.sh 2>&1 &&
 more/record-commands.sh &&
 ./host-tools.sh 2>&1 &&
 more/record-commands.sh &&
 ./simple-cross-compiler.sh $CROSS_COMPILER_HOST 2>&1 ||
 dienow} | tee build/logs/build-host-cc.txt | maybe_quiet

cp packages/MANIFEST build || dienow

# Adjust $CPUS so as not to overload the machine, max 2 build processes
# per gigabyte of RAM

if test ! -z $FORK && test -z $CPUS
{
  setvar MEGS = $(($(awk '/MemTotal:/{print $2}' /proc/meminfo)/1024))
  setvar TARGET_COUNT = $(find sources/targets -maxdepth 1 -type f | wc -l)
  export CPUS=$(($MEGS/($TARGET_COUNT*512)))
  test $CPUS -lt 1 && setvar CPUS = '1'
}

# Build all non-hw targets, possibly in parallel

more/for-each-target.sh \
  './build.sh $TARGET 2>&1 | tee build/logs/build-${TARGET}.txt'

# Run smoketest.sh for each non-hw target.

more/for-each-target.sh \
  'more/smoketest.sh $TARGET 2>&1 | tee build/logs/smoketest-$TARGET.txt'

# If we have a control image, build natively

for i in "$@"
{
  more/buildall-native.sh $1
}

more/smoketest-report.sh | tee build/logs/status.txt