#!/bin/bash

## Copyright (C) 2012 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## Copyright (C) 2021 Gavin Pacini
## 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

export_utm_packages() {
   ## create folder structure for UTM
   ## move image file
   ## copy configs
   mkdir --parents "${binary_image_utm_folder}/Data"
   $SUDO_TO_ROOT chown "$user_name:$user_name" "$binary_image_raw_file"
   ## copy instead of move the raw image
   ## disadvantage:
   ## - requires more disk space
   ## advantage:
   ## - makes this step idempotent, easier to test and debug
   ## - can CI test dm-prepare-release
   cp "$binary_image_raw_file" "${binary_image_utm_folder}/Data/${VMNAME}.raw"
   cp "$source_utm_file" "${binary_image_utm_folder}/config.plist"

   ## Fill in correct architecture and target in UTM template files.
   local utm_arch
   local utm_target
   if [ "${dist_build_target_arch:-}" = "arm64" ]; then
      utm_arch="aarch64"
      utm_target="virt"
   else
      utm_arch="x86_64"
      utm_target="q35"
   fi

   $str_replace_tool "_ARCH_"   "${utm_arch}"   "${binary_image_utm_folder}/config.plist"
   $str_replace_tool "_TARGET_" "${utm_target}" "${binary_image_utm_folder}/config.plist"

   ## Fill in correct flavor for raw image filename and VM name as it appears on UTM.
   $str_replace_tool "_FLAVOR_" "${VMNAME}" "${binary_image_utm_folder}/config.plist"

   ## TODO: This should be moved to dm-prepare-release.
   ##       But good enough to keep it here as long as UTM builds are not redistributed.
   ##
   ## Compress the utm folder into one archive respecting sparse (null) bytes
   ## dm-prepare-release also uses tar. Using similar options here.
   tar \
      --create \
      --verbose \
      --owner=0 --group=0 --numeric-owner \
      --mode=go=rX,u+rw,a-s \
      --sort=name \
      --sparse \
      --mtime='2015-10-21 00:00Z' \
      --gzip \
      --file="${dist_binary_build_folder}/${VMNAME}.utm.tar.gz" \
      "$binary_image_utm_folder"

   ## Safe disk space.
   safe-rm -r -- "${binary_image_utm_folder}"
}

main() {
   if [ "${dist_build_utm:-}" = "true" ]; then
      export_utm_packages
   else
      true "${green}INFO: Skipping ${BASH_SOURCE[0]}, because not using --target utm.${reset}"
   fi
}

main "$@"
