#!/usr/bin/env bash
# Build the rpki-explorer all-in-one image locally and export it as a tarball
# ready to transfer to a remote host (docker load on the other side).
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
OUT_DIR="${OUT_DIR:-$REPO_ROOT/target/rpki-explorer-image}"
IMAGE_NAME="${IMAGE_NAME:-rpki-explorer}"
GIT_REV="$(git -C "$REPO_ROOT" rev-parse --short HEAD)"
IMAGE_TAG="${IMAGE_TAG:-$GIT_REV}"

dirty_count="$(git -C "$REPO_ROOT" status --porcelain | wc -l)"

echo "[build] repo=$REPO_ROOT rev=$GIT_REV dirty_files=$dirty_count tag=$IMAGE_TAG"

docker build \
  --file "$REPO_ROOT/deploy/rpki-explorer/Dockerfile" \
  --build-arg "GIT_REV=$GIT_REV" \
  --tag "$IMAGE_NAME:$IMAGE_TAG" \
  "$REPO_ROOT"

mkdir -p "$OUT_DIR"
TARBALL="$OUT_DIR/rpki-explorer-$IMAGE_TAG.tar.gz"
docker save "$IMAGE_NAME:$IMAGE_TAG" | gzip > "$TARBALL"

IMAGE_ID="$(docker image inspect --format '{{.Id}}' "$IMAGE_NAME:$IMAGE_TAG")"
cat > "$OUT_DIR/rpki-explorer-$IMAGE_TAG.provenance.txt" <<EOF
git_rev=$GIT_REV
dirty_files=$dirty_count
build_time_utc=$(date -u +%Y-%m-%dT%H:%M:%SZ)
image=$IMAGE_NAME:$IMAGE_TAG
image_id=$IMAGE_ID
EOF

echo "[build] image tarball: $TARBALL"
echo "[build] provenance:    $OUT_DIR/rpki-explorer-$IMAGE_TAG.provenance.txt"
echo "[build] transfer:      cat '$TARBALL' | ssh root@<host> 'gunzip | docker load'"
