#!/usr/bin/env bash
# 10-load.sh — run on the AIR-GAPPED RHEL 9.6 host.
# Verifies the bundle, then loads the ZAP image into the chosen runtime.
#
#   ./10-load.sh            # autodetect: docker if present, else podman
#   ./10-load.sh docker     # load into Docker (use this on a Drone Docker runner)
#   ./10-load.sh podman     # load into Podman
#
# The Drone Docker runner and Podman keep SEPARATE image stores. Load into the
# runtime that will actually run the scan.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
source "$ROOT/config/versions.env"

runtime="${1:-}"
if [[ -z "$runtime" ]]; then
  if command -v docker >/dev/null; then runtime=docker; else runtime=podman; fi
fi
command -v "$runtime" >/dev/null || { echo "$runtime not found" >&2; exit 1; }

echo "== verifying bundle integrity =="
cd "$ROOT"
if [[ -f SHA256SUMS ]]; then
  sha256sum --check --quiet SHA256SUMS && echo "SHA256SUMS OK"
else
  echo "SHA256SUMS not present; checking image checksum only"
  sha256sum --check --status metadata/zap-image.sha256 && echo "image checksum OK"
fi

IMAGE_TAR="$ROOT/images/zaproxy-${ZAP_VERSION}-amd64.tar"
echo "== loading $(basename "$IMAGE_TAR") into $runtime =="
"$runtime" load -i "$IMAGE_TAR"

# The docker-archive carries the tag from config/versions.env; confirm it.
if "$runtime" image exists "$ZAP_IMAGE_LOCAL" 2>/dev/null \
   || "$runtime" image inspect "$ZAP_IMAGE_LOCAL" >/dev/null 2>&1; then
  echo "image available as $ZAP_IMAGE_LOCAL"
else
  echo "NOTE: loaded image tag differs; run '$runtime images' and retag to $ZAP_IMAGE_LOCAL"
fi

echo "== smoke test (network disabled) =="
"$runtime" run --rm --network=none "$ZAP_IMAGE_LOCAL" zap.sh -version
echo "PASS: ZAP image loaded and runs offline."
echo "Next: ./20-verify-offline.sh $runtime"
