#!/bin/bash

## Copyright (C) 2012 - 2023 ENCRYPTED SUPPORT LP <adrelanos@whonix.org>
## Copyright (C) 2021 Gavin Pacini
## See the file COPYING for copying conditions.

set -x
set -e

true "INFO: Currently running script: $BASH_SOURCE $@"

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

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

source pre
source colors
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}.raw" "${binary_image_utm_folder}/config.plist"

   ## 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"
}

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

main "$@"
