#!/usr/bin/env bash
# Shared driver for the copy-only "bundle" product images
# (probe / funke-pegasus / norsk-commentary / norsk-playout). Single-sourced in
# @norskvideo/ctl-dev-kit; each product's deployment/build-image.sh is a thin
# wrapper that sets the per-product facts and sources this file. Studio does NOT
# use this driver (it ships a --compile binary; see products/studio/deployment).
#
# The wrapper MUST set before sourcing:
#   PRODUCT_DIR   absolute path to the product workspace (backend/, frontend/,
#                 dashboards/, components/, package.json)
#   IMAGE_TAG     the image tag to build (the wrapper sets the product default)
#   PRODUCT_PORT  the container port docker-runner maps to (probe/funke 4321,
#                 commentary/playout 4322)
# Optional:
#   PRODUCT_BUILD_SCRIPT  workspace script that builds the host artifacts
#                         (default: build:no-lint)
#   BUN_VERSION           override the pinned bun (default from packageManager)
#
# Everything else is auto-detected off PRODUCT_DIR, so a product opts in just by
# having the directory/script — no per-product flag to keep in sync:
#   frontend/dist              the frontend workspace's build output
#   dashboards/                the dashboard workspace's build output
#   fleet-dashboards/          fleet dashboard bundles the product brings
#                              (its manifest's defaultDashboards)
#   components/lib             the components workspace's build output
#   native/                    native addon(s) (probe's signer) -> beside bundle
#   assets/                    product-template assets (funke's PNGs)
#   docs/generated/bundle/     the docs bundle (doc-guide buildBundle) -> docs/
#   scripts/runtime-images.ts  -> emits the norsk-ctl.runtime-images label
#
# Only backend/dist is required. A product with no frontend/dashboard/components
# workspace (reuters) stages those empty and builds the same as one that has all
# three (funke/probe/commentary).
set -euo pipefail

: "${PRODUCT_DIR:?build-bundle-image.sh: PRODUCT_DIR must be set by the wrapper}"
: "${IMAGE_TAG:?build-bundle-image.sh: IMAGE_TAG must be set by the wrapper}"
: "${PRODUCT_PORT:?build-bundle-image.sh: PRODUCT_PORT must be set by the wrapper}"
build_script="${PRODUCT_BUILD_SCRIPT:-build:no-lint}"

driver_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./common.sh
source "${driver_dir}/common.sh"

# Pin bun once from the product repo's packageManager so downstream helpers don't
# each re-walk the tree.
export BUN_VERSION="${BUN_VERSION:-$(product_bun_version "${PRODUCT_DIR}")}"

echo "==> building on host (${build_script})"
bun run --cwd "${PRODUCT_DIR}" "${build_script}"

stage="$(mktemp -d)"
trap 'rm -rf "${stage}"' EXIT

echo "==> staging artifacts"
mkdir -p "${stage}/backend" "${stage}/frontend/dist" "${stage}/components/lib" \
  "${stage}/dashboards" "${stage}/fleet-dashboards" "${stage}/native" "${stage}/assets" "${stage}/docs"
# The backend bundle is the one non-negotiable payload — every bundle product has
# one, so a missing dist is a broken build, not an absent workspace.
cp -R "${PRODUCT_DIR}/backend/dist" "${stage}/backend/dist"

# Frontend / dashboards / components are produced by the workspaces of the same
# name, so a product that has no such workspace never produces them (reuters:
# backend-only). Staged empty in that case, exactly as native/ and assets/ below
# — Dockerfile.bundle COPYs every one unconditionally, so the path must exist even
# when there is nothing to put in it.
if [ -d "${PRODUCT_DIR}/frontend/dist" ]; then
  cp -R "${PRODUCT_DIR}/frontend/dist/." "${stage}/frontend/dist/"
fi
if [ -d "${PRODUCT_DIR}/dashboards" ]; then
  cp -R "${PRODUCT_DIR}/dashboards/." "${stage}/dashboards/"
fi
# Fleet dashboards (norsk-ctl task 123): served by the control plane as the
# bundles its manifest's defaultDashboards name. Not under dashboards/, whose
# every directory is packed into each product template for Studio to serve.
if [ -d "${PRODUCT_DIR}/fleet-dashboards" ]; then
  cp -R "${PRODUCT_DIR}/fleet-dashboards/." "${stage}/fleet-dashboards/"
fi
if [ -d "${PRODUCT_DIR}/components/lib" ]; then
  cp -R "${PRODUCT_DIR}/components/lib/." "${stage}/components/lib/"
fi

# Native addon(s): staged beside the bundle. Strip the build host's RUNPATH (nix
# store / repo-local paths) so the shipped .node carries no build-host paths; its
# NEEDED libs resolve via the base image's default search path. Best-effort:
# only if patchelf is available.
if [ -d "${PRODUCT_DIR}/native" ]; then
  find "${PRODUCT_DIR}/native" -maxdepth 1 -name '*.node' -exec cp {} "${stage}/native/" \;
  if command -v patchelf >/dev/null 2>&1; then
    find "${stage}/native" -name '*.node' -exec patchelf --remove-rpath {} \;
  fi
fi

# Product-template assets (optional): copy contents into the always-staged dir.
if [ -d "${PRODUCT_DIR}/assets" ]; then
  cp -R "${PRODUCT_DIR}/assets/." "${stage}/assets/"
fi

# The docs bundle (optional): ONLY the built bundle, never the hand-written
# docs/ tree beside it (planning notes, customer folders).
if [ -d "${PRODUCT_DIR}/docs/generated/bundle" ]; then
  cp -R "${PRODUCT_DIR}/docs/generated/bundle/." "${stage}/docs/"
fi

# Runtime images the default templates launch, stamped on as a label so a
# golden-image bake can warm them with `docker inspect` + `docker pull` alone —
# no daemon, no license. Derived from the rendered compose (scripts/runtime-images.ts),
# never hardcoded. Products without that script simply don't carry the label.
label_args=()
if [ -f "${PRODUCT_DIR}/scripts/runtime-images.ts" ]; then
  echo "==> resolving runtime images for the norsk-ctl.runtime-images label"
  runtime_images="$(bun "${PRODUCT_DIR}/scripts/runtime-images.ts")"
  label_args+=(--label "norsk-ctl.runtime-images=${runtime_images}")
fi

echo "==> docker build ${IMAGE_TAG}"
docker build \
  --build-arg BASE_IMAGE="${PRODUCT_BASE_IMAGE}" \
  --build-arg BUN_IMAGE="$(product_bun_slim_image)" \
  --build-arg PRODUCT_PORT="${PRODUCT_PORT}" \
  "${label_args[@]}" \
  -f "${driver_dir}/Dockerfile.bundle" -t "${IMAGE_TAG}" "${stage}"

echo "==> built ${IMAGE_TAG}"
