#!/usr/bin/env bash
# 15-push-registry.sh — OPTIONAL, run once inside the air-gapped network.
# Copies every image archive of the bundle into an internal registry so
# several runners can share them, and prints the digests to pin.
#
#   ./15-push-registry.sh registry.internal.example[/prefix]
#
# Authenticate first: skopeo login registry.internal.example
# (skopeo copies straight from the archives; nothing is loaded locally).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
source "$ROOT/config/versions.env"
source "$ROOT/config/scanner-image.env"

REG="${1:?usage: $0 registry.internal.example[/prefix]}"
REG="${REG%/}"
command -v skopeo >/dev/null || { echo "skopeo is required (dnf install skopeo)" >&2; exit 1; }

out="$ROOT/metadata/registry-push-$(date -u +%Y%m%dT%H%M%SZ).tsv"
printf 'source_tag\tdestination\tdigest\n' > "$out"

# push ARCHIVE SOURCE_TAG DEST_REPO_PATH DEST_TAG...
push() {
  local tar="$1" src="$2" path="$3"; shift 3
  local tag first=""
  for tag in "$@"; do
    echo "-- $src -> $REG/$path:$tag"
    skopeo copy --quiet --digestfile "$ROOT/metadata/.digest" \
      "docker-archive:$ROOT/$tar:$src" "docker://$REG/$path:$tag"
    first="${first:-$(cat "$ROOT/metadata/.digest")}"
    printf '%s\t%s\t%s\n' "$src" "$REG/$path:$tag" "$(cat "$ROOT/metadata/.digest")" >> "$out"
  done
  rm -f "$ROOT/metadata/.digest"
  echo "   pin as: $REG/$path@$first"
}

push "images/drone-server-${DRONE_VERSION}-amd64.tar"         "$DRONE_IMAGE_LOCAL"  drone/drone               "$DRONE_VERSION"
push "images/drone-runner-docker-${RUNNER_VERSION}-amd64.tar" "$RUNNER_IMAGE_LOCAL" drone/drone-runner-docker "$RUNNER_VERSION"
push "images/drone-git-amd64.tar"                             "$GIT_IMAGE_LOCAL"    drone/git                 "latest"
push "$SCANNER_IMAGE_ARCHIVE" "$SCANNER_IMAGE" devsecops/drone-scanners "$SCANNER_DATA_DATE" stable

echo
echo "Recorded in $(basename "$out"). Set on every runner:"
echo "  DRONE_RUNNER_CLONE_IMAGE=$REG/drone/git:latest   (or the @sha256 digest above)"
echo "and in pipelines:"
echo "  image: $REG/devsecops/drone-scanners:stable   pull: always"
