#!/bin/sh
# build-in-container.sh — build the bee ISO inside the Debian builder container.

set -e

REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
BUILDER_DIR="${REPO_ROOT}/iso/builder"
CONTAINER_TOOL="${CONTAINER_TOOL:-docker}"
IMAGE_TAG="${BEE_BUILDER_IMAGE:-bee-iso-builder}"
BUILDER_PLATFORM="${BEE_BUILDER_PLATFORM:-linux/amd64}"
CACHE_DIR="${BEE_BUILDER_CACHE_DIR:-${REPO_ROOT}/dist/container-cache}"
AUTH_KEYS=""
REBUILD_IMAGE=0
CLEAN_CACHE=0
VARIANT="all"

. "${BUILDER_DIR}/VERSIONS"

while [ $# -gt 0 ]; do
    case "$1" in
        --cache-dir)
            CACHE_DIR="$2"
            shift 2
            ;;
        --rebuild-image)
            REBUILD_IMAGE=1
            shift
            ;;
        --authorized-keys)
            AUTH_KEYS="$2"
            shift 2
            ;;
        --clean-build)
            CLEAN_CACHE=1
            REBUILD_IMAGE=1
            shift
            ;;
        --variant)
            VARIANT="$2"
            shift 2
            ;;
        *)
            echo "unknown arg: $1" >&2
            echo "usage: $0 [--cache-dir /path] [--rebuild-image] [--clean-build] [--authorized-keys /path/to/authorized_keys] [--variant nvidia|nvidia-legacy|amd|nogpu|all]" >&2
            exit 1
            ;;
    esac
done

case "$VARIANT" in
    nvidia|nvidia-legacy|amd|nogpu|all) ;;
    *) echo "unknown variant: $VARIANT (expected nvidia, nvidia-legacy, amd, nogpu, or all)" >&2; exit 1 ;;
esac

if [ "$CLEAN_CACHE" = "1" ]; then
    echo "=== cleaning build cache: ${CACHE_DIR} ==="
    rm -rf "${CACHE_DIR:?}/go-build" \
           "${CACHE_DIR:?}/go-mod" \
           "${CACHE_DIR:?}/tmp" \
           "${CACHE_DIR:?}/bee" \
           "${CACHE_DIR:?}/lb-packages"
    echo "=== cleaning live-build work dirs ==="
    rm -rf "${REPO_ROOT}/dist/live-build-work-nvidia"
    rm -rf "${REPO_ROOT}/dist/live-build-work-nvidia-legacy"
    rm -rf "${REPO_ROOT}/dist/live-build-work-amd"
    rm -rf "${REPO_ROOT}/dist/live-build-work-nogpu"
    rm -rf "${REPO_ROOT}/dist/overlay-stage-nvidia"
    rm -rf "${REPO_ROOT}/dist/overlay-stage-nvidia-legacy"
    rm -rf "${REPO_ROOT}/dist/overlay-stage-amd"
    rm -rf "${REPO_ROOT}/dist/overlay-stage-nogpu"
    echo "=== caches cleared, proceeding with build ==="
fi

if ! command -v "$CONTAINER_TOOL" >/dev/null 2>&1; then
    echo "container tool not found: $CONTAINER_TOOL" >&2
    exit 1
fi

PLATFORM_OS="${BUILDER_PLATFORM%/*}"
PLATFORM_ARCH="${BUILDER_PLATFORM#*/}"
if [ -z "$PLATFORM_OS" ] || [ -z "$PLATFORM_ARCH" ] || [ "$PLATFORM_OS" = "$BUILDER_PLATFORM" ]; then
    echo "invalid BEE_BUILDER_PLATFORM: ${BUILDER_PLATFORM} (expected os/arch, e.g. linux/amd64)" >&2
    exit 1
fi

if [ -n "$AUTH_KEYS" ]; then
    [ -f "$AUTH_KEYS" ] || { echo "authorized_keys not found: $AUTH_KEYS" >&2; exit 1; }
    AUTH_KEYS_ABS="$(cd "$(dirname "$AUTH_KEYS")" && pwd)/$(basename "$AUTH_KEYS")"
    AUTH_KEYS_DIR="$(dirname "$AUTH_KEYS_ABS")"
    AUTH_KEYS_BASE="$(basename "$AUTH_KEYS_ABS")"
fi

mkdir -p \
    "${CACHE_DIR}" \
    "${CACHE_DIR}/go-build" \
    "${CACHE_DIR}/go-mod" \
    "${CACHE_DIR}/tmp" \
    "${CACHE_DIR}/bee"

IMAGE_REF="${IMAGE_TAG}:debian${DEBIAN_VERSION}"

image_matches_platform() {
    actual_platform="$("$CONTAINER_TOOL" image inspect --format '{{.Os}}/{{.Architecture}}' "${IMAGE_REF}" 2>/dev/null || true)"
    [ "$actual_platform" = "${BUILDER_PLATFORM}" ]
}

NEED_BUILD_IMAGE=0
if [ "$REBUILD_IMAGE" = "1" ]; then
    NEED_BUILD_IMAGE=1
elif ! "$CONTAINER_TOOL" image inspect "${IMAGE_REF}" >/dev/null 2>&1; then
    NEED_BUILD_IMAGE=1
elif ! image_matches_platform; then
    actual_platform="$("$CONTAINER_TOOL" image inspect --format '{{.Os}}/{{.Architecture}}' "${IMAGE_REF}" 2>/dev/null || echo unknown)"
    echo "=== rebuilding builder image ${IMAGE_REF}: platform mismatch (${actual_platform} != ${BUILDER_PLATFORM}) ==="
    NEED_BUILD_IMAGE=1
fi

if [ "$NEED_BUILD_IMAGE" = "1" ]; then
    "$CONTAINER_TOOL" build \
        --platform "${BUILDER_PLATFORM}" \
        --build-arg GO_VERSION="${GO_VERSION}" \
        -t "${IMAGE_REF}" \
        "${BUILDER_DIR}"
else
    echo "=== using existing builder image ${IMAGE_REF} (${BUILDER_PLATFORM}) ==="
fi

# Build base docker run args (without --authorized-keys)
build_run_args() {
    _variant="$1"
    _auth_arg=""
    if [ -n "$AUTH_KEYS" ]; then
        _auth_arg="--authorized-keys /tmp/bee-authkeys/${AUTH_KEYS_BASE}"
    fi
    echo "run --rm --privileged \
        --platform ${BUILDER_PLATFORM} \
        -v ${REPO_ROOT}:/work \
        -v ${CACHE_DIR}:/cache \
        ${AUTH_KEYS:+-v ${AUTH_KEYS_DIR}:/tmp/bee-authkeys:ro} \
        -e BEE_CONTAINER_BUILD=1 \
        -e GOCACHE=/cache/go-build \
        -e GOMODCACHE=/cache/go-mod \
        -e TMPDIR=/cache/tmp \
        -e BEE_CACHE_DIR=/cache/bee \
        -w /work \
        ${IMAGE_REF} \
        sh /work/iso/builder/build.sh --variant ${_variant} ${_auth_arg}"
}

run_variant() {
    _v="$1"
    echo "=== building variant: ${_v} ==="
    if [ -n "$AUTH_KEYS" ]; then
        "$CONTAINER_TOOL" run --rm --privileged \
            --platform "${BUILDER_PLATFORM}" \
            -v "${REPO_ROOT}:/work" \
            -v "${CACHE_DIR}:/cache" \
            -v "${AUTH_KEYS_DIR}:/tmp/bee-authkeys:ro" \
            -e BEE_CONTAINER_BUILD=1 \
            -e GOCACHE=/cache/go-build \
            -e GOMODCACHE=/cache/go-mod \
            -e TMPDIR=/cache/tmp \
            -e BEE_CACHE_DIR=/cache/bee \
            -e BEE_REQUIRE_MEMTEST=1 \
            -w /work \
            "${IMAGE_REF}" \
            sh /work/iso/builder/build.sh --variant "${_v}" \
                --authorized-keys "/tmp/bee-authkeys/${AUTH_KEYS_BASE}"
    else
        "$CONTAINER_TOOL" run --rm --privileged \
            --platform "${BUILDER_PLATFORM}" \
            -v "${REPO_ROOT}:/work" \
            -v "${CACHE_DIR}:/cache" \
            -e BEE_CONTAINER_BUILD=1 \
            -e GOCACHE=/cache/go-build \
            -e GOMODCACHE=/cache/go-mod \
            -e TMPDIR=/cache/tmp \
            -e BEE_CACHE_DIR=/cache/bee \
            -e BEE_REQUIRE_MEMTEST=1 \
            -w /work \
            "${IMAGE_REF}" \
            sh /work/iso/builder/build.sh --variant "${_v}"
    fi
}

case "$VARIANT" in
    nvidia)
        run_variant nvidia
        ;;
    nvidia-legacy)
        run_variant nvidia-legacy
        ;;
    amd)
        run_variant amd
        ;;
    nogpu)
        run_variant nogpu
        ;;
    all)
        run_variant nvidia
        run_variant nvidia-legacy
        run_variant amd
        run_variant nogpu
        ;;
esac
