#!/usr/bin/env bash

# Copyright (c) 2025-2026 Tigera, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This script is run on the test VM, to load the component-specific test
# artifacts, which have already been downloaded to /tmp.

set -ex

ARCH=${ARCH:-amd64}
REPO_ROOT=$(cd "$(dirname "$0")/../.." && pwd)

# image-ref strings must match exactly what the .image.created-* recipes in
# lib.Makefile write, so hack/image-exists can re-find them in the daemon.
# Item format: "<tarball-prefix>:<marker-dir>:<image-ref>".
loaded_any=0
calico_image=
for item in \
    calico-image:cmd/calico:calico:latest-${ARCH} \
    node-image:node:node:latest-${ARCH} \
    whisker-image:whisker:whisker:latest-${ARCH}; do
  tarball="${item%%:*}.tar.zst"
  rest="${item#*:}"
  marker_dir="${rest%%:*}"
  image_ref="${rest#*:}"
  if [ -f "/tmp/${tarball}" ]; then
    echo "Loading cached ${tarball}..."
    # The tarballs carry the registry-prefixed tag, not the ref the stamp records.
    loaded=$(zstd -dc "/tmp/${tarball}" | docker load | sed -n 's/^Loaded image: //p' | head -1)
    if [ -z "${loaded}" ]; then
      echo "ERROR: ${tarball} loaded no image; ${image_ref} would be built from source."
      exit 1
    fi
    if [ "${loaded}" != "${image_ref}" ]; then
      docker tag "${loaded}" "${image_ref}"
    fi
    mkdir -p "${REPO_ROOT}/${marker_dir}"
    # Write the image ref so hack/image-exists treats the stamp as
    # backed by a concrete image (not just a touched empty file), and
    # so a pruned image forces a rebuild via MISSING-IMAGE.
    echo "${image_ref}" > "${REPO_ROOT}/${marker_dir}/.image.created-${ARCH}"
    rm -f "/tmp/${tarball}"
    loaded_any=1
    if [ "${marker_dir}" = cmd/calico ]; then
      calico_image="${image_ref}"
    fi
  else
    echo "WARNING: /tmp/${tarball} missing; ${image_ref} will be built from source."
  fi
done

# The k8st suite mounts cmd/calico/bin/calico-$ARCH, which only the image build
# we just skipped would have produced. Take it out of the image instead.
if [ -n "${calico_image}" ]; then
  calico_bin="${REPO_ROOT}/cmd/calico/bin/calico-${ARCH}"
  mkdir -p "$(dirname "${calico_bin}")"
  ctr=$(docker create "${calico_image}")
  docker cp "${ctr}:/usr/bin/calico" "${calico_bin}"
  docker rm -f "${ctr}" > /dev/null
  chmod +x "${calico_bin}"
fi

# Stub LIBBPF_MARKER so kind-build-images doesn't drag the cached node/cmd/calico
# image stamps back out-of-date by rebuilding libbpf.a (whose freshly-built mtime
# would be newer than the stamps). Only relevant when at least one image was
# loaded — otherwise let the normal build path produce the real artifact.
if [ "${loaded_any}" = 1 ]; then
  libbpf_stub="${REPO_ROOT}/felix/bpf-gpl/libbpf/src/${ARCH}/libbpf.a"
  mkdir -p "$(dirname "${libbpf_stub}")"
  : > "${libbpf_stub}"
  touch -d '2000-01-01' "${libbpf_stub}"
fi
