#!/bin/bash
# Build webrtcpush and its RV1106 deployment bundle in the SDK VM.
set -euo pipefail
export LC_ALL=C

HERE="$(cd "$(dirname "$0")/.." && pwd)"
cd "$HERE"

export RV1106_SDK="${RV1106_SDK:-$HOME/rv1106sdk/luckfox-pico}"
export WEBRTCPUSH_DEPS="${WEBRTCPUSH_DEPS:-$HERE/third_party/install-mbedtls-3.6.6}"
BUILD_DIR="${WEBRTCPUSH_BUILD_DIR:-build-mbedtls-3.6.6}"
TOOLCHAIN_BIN="$RV1106_SDK/tools/linux/toolchain/arm-rockchip830-linux-uclibcgnueabihf/bin"
export PATH="$TOOLCHAIN_BIN:$PATH"

printf 'SDK:   %s\n' "$RV1106_SDK"
printf 'deps:  %s\n' "$WEBRTCPUSH_DEPS"
printf 'build: %s\n' "$BUILD_DIR"

printf '[1/3] Build version-matched dependencies\n'
bash third_party/build_deps.sh all

printf '[2/3] Configure webrtcpush\n'
cmake -S . -B "$BUILD_DIR" \
  -DCMAKE_TOOLCHAIN_FILE=cmake/toolchain-rv1106.cmake \
  -DCMAKE_BUILD_TYPE=Release

printf '[3/3] Build executable and deployment archive\n'
cmake --build "$BUILD_DIR" -j"$(nproc)" --target webrtcpush
cmake --build "$BUILD_DIR" -j"$(nproc)" --target deploy

printf '\nBuild complete:\n'
printf '  executable: %s/%s\n' "$BUILD_DIR" webrtcpush
printf '  directory:  %s/%s\n' "$BUILD_DIR" deploy
printf '  BusyBox tar: %s/%s\n' "$BUILD_DIR" webrtcpush_deploy.tar
printf '  gzip tar:   %s/%s\n' "$BUILD_DIR" webrtcpush_deploy.tar.gz
