#!/usr/bin/env bash
# Harvest the dynamic-only vcpkg libs (usd 26.3 + tbb 2022.3.0) that the LFS
# runtime bundle is missing: lfs_pod_build.sh archived build/ with
# --exclude='vcpkg_installed', which is exactly where vcpkg puts them.
#
# Runs on a throwaway CPU pod (ubuntu:24.04). Reproduces the ABI of the original
# build: same vcpkg baseline (from LichtFeld-Studio@16047487 vcpkg.json), same
# version overrides, same triplet (x64-linux), same compiler (noble gcc-14).
# Uploads vcpkg_installed/x64-linux/lib/*.so* as usd_tbb_libs.tgz.
set -uo pipefail
BASE="https://gitea.cyango.com/api/packages/gustavo.domingues/generic/lfs-build/v1"
LOG=/var/log/harvest.log
exec > >(tee -a "$LOG") 2>&1
put() { curl -s -X DELETE -H "Authorization: token ${GITEA_TOKEN}" "$BASE/$1" >/dev/null 2>&1
  curl -s -X PUT -H "Authorization: token ${GITEA_TOKEN}" \
    -H "Content-Type: application/octet-stream" --data-binary @"$2" "$BASE/$1" >/dev/null; }
mark() { printf '%s\n' "$2" > /tmp/mark.txt; put "$1" /tmp/mark.txt; echo "[mark] $1: $2"; }
fail() { tail -c 8000 "$LOG" > /tmp/failtail.txt; put "HARVEST-FAILED.txt" /tmp/failtail.txt
  echo "[FAILED] $1"; sleep 1800; exit 1; }

heartbeat() { while true; do
  { echo "== $(date -u) elapsed=${SECONDS}s load:$(cat /proc/loadavg)"
    echo "== log tail:"; tail -c 2500 "$LOG"; } > /tmp/live.txt 2>&1
  put "HARVEST-LIVE.log" /tmp/live.txt
  sleep 60; done; }
heartbeat & HB=$!; trap 'kill $HB 2>/dev/null' EXIT

mark "HARVEST-00-start.txt" "$(date -u) nproc=$(nproc)"

export DEBIAN_FRONTEND=noninteractive
apt-get update && apt-get install -y --no-install-recommends \
  git curl zip unzip tar ca-certificates build-essential gcc-14 g++-14 \
  pkg-config bison flex autoconf automake libtool python3 linux-libc-dev \
  || fail apt
export CC=gcc-14 CXX=g++-14
mark "HARVEST-01-deps.txt" "gcc $(gcc-14 --version | head -1)"

git clone --quiet https://github.com/microsoft/vcpkg /opt/vcpkg || fail vcpkg-clone
/opt/vcpkg/bootstrap-vcpkg.sh -disableMetrics || fail bootstrap
mark "HARVEST-02-vcpkg.txt" "bootstrapped"

mkdir -p /harvest && cd /harvest
cat > vcpkg.json <<'EOF'
{
  "builtin-baseline": "c3867e714dd3a51c272826eea77267876517ed99",
  "dependencies": ["tbb", "usd"],
  "overrides": [
    { "name": "tbb", "version": "2022.3.0" },
    { "name": "usd", "version": "26.3" }
  ]
}
EOF
/opt/vcpkg/vcpkg install --triplet x64-linux || fail install
mark "HARVEST-03-built.txt" "$(ls vcpkg_installed/x64-linux/lib/*.so* 2>/dev/null | wc -l) shared libs"

cd vcpkg_installed/x64-linux/lib
ls -la ./*.so* || fail no-libs
tar -czhf /tmp/usd_tbb_libs.tgz ./*.so* || fail tar
put "usd_tbb_libs.tgz" /tmp/usd_tbb_libs.tgz
mark "HARVEST-DONE.txt" "size=$(stat -c%s /tmp/usd_tbb_libs.tgz) libs=$(ls ./*.so* | tr '\n' ' ')"
echo "HARVEST_OK"
sleep 900
