#!/bin/sh

set -e
cd "$(dirname "$0")"

# Run Script
RUN="$(pwd)/run.sh"
rm -f "${RUN}"
out() {
    echo "$1" >> "${RUN}"
}
out '#!/bin/sh'
out 'set -e'
out 'cd "$(dirname "$0")"'
chmod +x "${RUN}"

# Create Build Directory
dir() {
    mkdir -p "$1"
    cd "$1"
}
dir build

# Build Host Component
build_example_part() {
    dir "$1"
    cmake -GNinja "../../$1"
    cmake --build .
}
build_example_part host
out "export LD_LIBRARY_PATH=\"$(pwd):\${LD_LIBRARY_PATH}\""
out "export PATH=\"$(pwd)/runtime:\${PATH}\""
cd ../

# Build Guest Component
build_example_part guest

# Finalize Script
out "export QEMU_LD_PREFIX=/usr/arm-linux-gnueabihf"
out "exec runtime \"$(pwd)/example\""

# Done
echo 'BUILD COMPLETE!'
echo 'See ./run.sh'