#!/bin/bash
set -eE -o pipefail          # -E ⇒ trap inherits in functions/subshells

stage=2                      # 1 = build, 2 = infrastructure

trap 'case $stage in
          0) exit 0;;        # any build command succeeded
          1) exit 1;;        # any build command failed
          2) exit 2;;        # any test command failed
          *) exit $?;        # fallback for unexpected errors
      esac' ERR

# Build metadata:
#   arch: arm
#   compiler: gcc-14
#   defconfig: vexpress_defconfig
#   fragments: []
#   src_tarball: https://files-staging.kernelci.org/linux-kernelci-staging-next-staging-next-20260129.1.tar.gz
#   apijobname: kbuild-gcc-14-arm-vexpress_defconfig
#   cross_compile: arm-linux-gnueabihf-

# Set environment variables
export ARCH=arm
export CROSS_COMPILE=arm-linux-gnueabihf-
export INSTALL_MOD_PATH=_modules_
export INSTALL_MOD_STRIP=1
export INSTALL_DTBS_PATH=_dtbs_
export CC=gcc-14
export HOSTCC=gcc-14
set -x
touch /tmp/kci/artifacts/build.log
tail -f /tmp/kci/artifacts/build.log &
tailpid=$!
exec >>/tmp/kci/artifacts/build.log 2>&1
# Download tarball
cd /tmp/kci
wget -c -t 10 --retry-on-host-error "https://files-staging.kernelci.org/linux-kernelci-staging-next-staging-next-20260129.1.tar.gz" -O linux.tgz
tar -xzf linux.tgz -C /tmp/kci/linux --strip-components=1

# Starting job fetch_firmware
echo -----log:fetch_firmware-----
echo job:fetch_firmware=running >> /tmp/kci/artifacts/state.txt
echo jobsts:fetch_firmware=$(date +%s) >> /tmp/kci/artifacts/state.txt
cp /data/linux-firmware.tar.gz .
tar -xzf linux-firmware.tar.gz
cd linux-firmware
./copy-firmware.sh /tmp/kci/firmware
cd ..
# Finishing job fetch_firmware
echo job:fetch_firmware=done >> /tmp/kci/artifacts/state.txt
echo jobets:fetch_firmware=$(date +%s) >> /tmp/kci/artifacts/state.txt

# Starting job build_tuxmake
echo -----log:build_tuxmake-----
echo job:build_tuxmake=running >> /tmp/kci/artifacts/state.txt
echo jobsts:build_tuxmake=$(date +%s) >> /tmp/kci/artifacts/state.txt
cd /tmp/kci/linux
tuxmake --runtime=null --target-arch=arm --toolchain=gcc-14 --output-dir=/tmp/kci/artifacts --kconfig=vexpress_defconfig --kconfig-add=/tmp/kci/artifacts/fragments/0.config kernel modules dtbs kselftest
cd ..
# Finishing job build_tuxmake
echo job:build_tuxmake=done >> /tmp/kci/artifacts/state.txt
echo jobets:build_tuxmake=$(date +%s) >> /tmp/kci/artifacts/state.txt

echo Build script is completed, tail will be killed now
stage=0
set +eE -o pipefail
trap - ERR

kill $tailpid || true
stage=0
kill $tailpid || true
