#!/usr/bin/env bash
# 99-package.sh — run on the CONNECTED builder after 05-build-scanner-image.sh
# (and ideally 30-verify-offline.sh). Produces one transferable tarball plus
# SHA256SUMS for the whole bundle.
#
# build/ (DB staging + builder tools, ~5 GB) is NOT shipped: the vulnerability
# data travels inside the scanner image archive.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
source "$ROOT/config/versions.env"
[[ -f "$ROOT/config/scanner-image.env" ]] || { echo "run scripts/05-build-scanner-image.sh first" >&2; exit 1; }
source "$ROOT/config/scanner-image.env"
test -s "$ROOT/$SCANNER_IMAGE_ARCHIVE" || { echo "missing $SCANNER_IMAGE_ARCHIVE" >&2; exit 1; }

cd "$ROOT"
echo "computing SHA256SUMS over the bundle..."
find . -type f \
  ! -name SHA256SUMS \
  ! -path './build/*' \
  ! -path './.git/*' \
  ! -name '*.pyc' \
  -print0 | sort -z | xargs -0 sha256sum > SHA256SUMS
echo "$(wc -l < SHA256SUMS) files listed in SHA256SUMS"

out="$ROOT/../devsecops-drone-offline-${DRONE_VERSION}-${SCANNER_DATA_DATE}-linux-amd64.tar.gz"
compress=gzip
command -v pigz >/dev/null && compress=pigz
echo "creating $(basename "$out") with $compress (image archives are large; this takes a few minutes)..."
tar --create --use-compress-program="$compress" --file "$out.part" \
  --exclude="$(basename "$ROOT")/build" \
  --exclude='*.pyc' --exclude='__pycache__' \
  --directory "$ROOT/.." "$(basename "$ROOT")"
mv "$out.part" "$out"
(cd "$(dirname "$out")" && sha256sum "$(basename "$out")") | tee "$out.sha256"
echo "done. Transfer $(basename "$out") and its .sha256 to the air-gapped network."
