#!/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
export LC_ALL=C

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

convert_raw_to_qcow2() {
   if [ ! "${dist_build_qcow2:-}" = "true" ]; then
      true "${green}INFO: Skipping ${BASH_SOURCE[0]}, because dist_build_qcow2 is not set to true.${reset}"
      return 0
   fi

   mkdir --parents "${dist_binary_build_folder}"

   ## Debugging.
   qemu-img \
      info \
         "${binary_image_raw_file}"

   ## Create qcow2 image form raw image.
   ## VMSIZE defaults to 100G as per help-steps/variables.
   ##
   ## Minimum cluster size with extended_l2=on is 16K according to
   ## https://www.qemu.org/docs/master/interop/qcow2.html, we want a larger
   ## cluster size than that for performance.
   ##
   ## NOTE: In some circumstances, better performance might be reachable by
   ## using a cluster size of 128 KiB, but this may require a lot of factors to
   ## be right (4K alignment, right filesystem, good filesystem block size,
   ## right storage media) to be the case. Might be worth benchmarking in the
   ## future, but for now, it's easiest to stick with 2 MiB.
   qemu-img \
      convert \
         -p \
         -O qcow2 \
         -o compat=1.1 \
         -o extended_l2=on,cluster_size=2M \
         -o preallocation=metadata \
         "${binary_image_raw_file}" \
         "${binary_image_qcow2_file}"

   ## Debugging.
   qemu-img \
      info \
         "${binary_image_qcow2_file}"

   true
}

main() {
   if [ "${dist_build_qcow2:-}" = "true" ]; then
      convert_raw_to_qcow2
   else
      true "${green}INFO: Skipping ${BASH_SOURCE[0]}, because dist_build_qcow2 is not set to 'true'.${reset}"
   fi
}

main "$@"
