#!/bin/bash

## Copyright (C) 2026 - 2026 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

## AI-Assisted

## Copy the dry-run lane's built images OUT of the (still-running) build
## container into a runner-owned directory that actions/upload-artifact can read.
## The lane BUILDS a real '.qcow2.libvirt.xz' and its '.dm-buildinfo'; publishing
## them is what makes the lane's output inspectable and lets
## dm-repro-verify-against-ci compare a local dry-run against CI. The build writes
## to the build user's home inside the container, not the bind-mounted workspace,
## so this must run while the container is alive.
##
## Args: $1 = container name, $2 = destination dir (created if absent).

set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit
shopt -s shift_verbose
export LC_ALL=C

container="${1:-}"
dest_dir="${2:-}"
if [ -z "${container}" ] || [ -z "${dest_dir}" ]; then
   printf '%s\n' "usage: ${BASH_SOURCE[0]} <container> <dest-dir>" >&2
   exit 64
fi

## sudo for the mkdir: the privileged container ran ./ci/dry-run as ROOT in this
## bind-mounted workspace, so it is root-owned by now and an unprivileged mkdir
## fails. The workflow's own "Reclaim workspace ownership" step fixes that, but it
## runs LATER -- after the container is torn down, and 'docker cp' needs it alive.
sudo mkdir --parents -- "${dest_dir}"
## '|| true' on the copy alone, never on the assertion below: a lane that produced
## nothing must fail at the upload, not here.
sudo docker cp "${container}:/home/builder/derivative-binary/." "${dest_dir}/" || true
## Hand it back before upload-artifact reads it.
sudo chown --recursive -- "$(id -u):$(id -g)" "${dest_dir}"
find "${dest_dir}" -type f \( -name '*.qcow2.libvirt.xz' -o -name '*.dm-buildinfo' \) -print
