#!/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

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.
   qemu-img \
      convert \
         -p \
         -O qcow2 \
         -o cluster_size=2M \
         -o extended_l2=on,cluster_size=128k \
         -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 "$@"
