#!/bin/bash

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

set -x
set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit
shopt -s shift_verbose

true "INFO: Currently running script: ${BASH_SOURCE[0]} $*"

MYDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

cd "${MYDIR}"
cd ..
cd help-steps

source pre
source variables

prepare-release(){
   ## VirtualBox OVA export inside the amd64 cowbuilder chroot:
   ##
   ## 'build-steps.d/4600_create-vbox-vm' creates the VirtualBox VM inside an
   ## amd64 cowbuilder chroot (because VirtualBox is not packaged for arm64
   ## Linux), so the VirtualBox registry lives inside that chroot, not on the
   ## build host. Accordingly 'dm-prepare-release' (in
   ## 'Kicksecure/developer-meta-files', a submodule under
   ## '$dist_developer_meta_files_folder') runs only the 'VBoxManage'-using
   ## portion of its 'virtualbox_export' inside that same chroot via
   ## 'cowbuilder --execute' (chroot script
   ## 'help-steps/pbuilder-chroot-script-export-vbox-vm'), writing the '.ova'
   ## to the bind-mounted '$binary_image_ova_file' so it lands on the host.
   ## Signing and upload stay on the host, where the operator's credentials
   ## already are.
   "${dist_developer_meta_files_folder}/usr/bin/dm-prepare-release" "$@"

   true
}

export-signing-pubkeys(){
   ## Copy the auto-generated signing public keys next to the build output so the
   ## CI 'repro-checksums' artifact can include them.
   if [ -z "${binary_build_folder_dist:-}" ] || [ ! -d "${binary_build_folder_dist}" ]; then
      true "INFO: ${BASH_SOURCE[0]}: no binary_build_folder_dist; skipping public-key export."
      return 0
   fi
   if [ -n "${signify_public_key:-}" ] && [ -r "${signify_public_key}" ]; then
      cp -- "${signify_public_key}" "${binary_build_folder_dist}/derivative-maker-signify.pub" || true
   fi
   if [ -n "${DEBEMAIL:-}" ] && has sq; then
      ## NOTE: If the build machine has a malicious key imported into sq that
      ## bears the signer's email address but doesn't belong to the signer,
      ## this will export the bad public key too and potentially cause
      ## confusion.
      sq cert export --cert-email "${DEBEMAIL}" \
         > "${binary_build_folder_dist}/derivative-maker-openpgp.asc" 2>/dev/null || true
   fi
   true
}

main() {
   prepare-release "$@"
   export-signing-pubkeys "$@"
}

main "$@"
