#!/bin/bash

## Copyright (C) 2012 - 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

export-libvirt-xml() {
   local xml_dir available

   mkdir --parents "${binary_build_folder_dist}"

   if [ -z "${libvirt_source_kvm_file}" ]; then
      error "libvirt_source_kvm_file is empty, so the flavor did not resolve to a
VM name. It is set in help-steps/variables from SHORT_VMNAME.
  flavor: ${dist_build_flavor:-unset}"
   fi

   if [ ! -r "${libvirt_source_kvm_file}" ]; then
      xml_dir="$( dirname -- "${libvirt_source_kvm_file}" )"
      if [ -d "${xml_dir}" ]; then
         available="$( ls -1 -- "${xml_dir}" )"
      else
         available="  (${xml_dir} does not exist)"
      fi
      error "No libvirt XML exists for this flavor and target combination:
  flavor       : ${dist_build_flavor:-unset}
  expected file: ${libvirt_source_kvm_file}

Available libvirt XML files:
${available}"
   fi

   cp -- "${libvirt_source_kvm_file}" "${libvirt_target_kvm_file}"

   #if [ "${dist_build_type_short:-}" = "kicksecure" ]; then
      #true
   #elif [ "${dist_build_type_short:-}" = "custom-workstation" ]; then
      #true
   #else
      ## The Whonix-External / Whonix-Internal libvirt network XML files were
      ## removed from the 'libvirt-dist' package, so there is nothing to copy
      ## here anymore. Left commented (not deleted) to document the former
      ## behavior in case per-network XML returns.
      #cp "$libvirt_source_network_file_external" "$libvirt_target_network_file_external"
      #cp "$libvirt_source_network_file_internal" "$libvirt_target_network_file_internal"
      #true
   #fi
}

main() {
#    if [ "${dist_build_host_operating_system:-}" = "true" ]; then
#       true "${green}INFO: Skipping ${BASH_SOURCE[0]}, because dist_build_host_operating_system is '$dist_build_host_operating_system', ok.${reset}"
#       return 0
#    fi

   if [ "${dist_build_source_run:-}" = "true" ]; then
      true "${green}INFO: Skipping ${BASH_SOURCE[0]}, because this is a source build.${reset}"
      return 0
   fi

   if [ "${dist_build_raw:-}" = "true" ]; then
      ## Required for Linux libvirt KVM raw image builds.
      ## Interest to maintain arm64 Linux libvirt KVM raw images has been
      ## indicated by HulaHoop until qcow2 image builds are fixed.
      ## XXX: Superfluous for non-libvirt raw image builds.
      export-libvirt-xml "$@"
   elif [ "${dist_build_qcow2:-}" = "true" ]; then
      export-libvirt-xml "$@"
   else
      true "${green}INFO: Skipping ${BASH_SOURCE[0]}, because dist_build_qcow2 is not set to 'true'.${reset}"
   fi
}

main "$@"
