#!/bin/bash

## Copyright (C) 2012 - 2023 ENCRYPTED SUPPORT LP <adrelanos@whonix.org>
## 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"

source ~/derivative-maker/help-steps/pre
source ~/derivative-maker/help-steps/colors
source ~/derivative-maker/help-steps/variables

error_handler_mount-vdi() {
   : echo "
${red}${bold}BASH_COMMAND${reset}: $BASH_COMMAND
${red}${bold}ERROR $BASH_SOURCE: | caller: $(caller)${reset}
"
   exit 1
}

mount_vdi() {
   trap "error_handler_mount-vdi" ERR INT TERM

   $SUDO_TO_ROOT sync

   ## Ensure powered is off. Otherwise disk corruption is at high risk.
   VBoxManage controlvm "$VMNAME" poweroff || true
   $SUDO_TO_ROOT sync

   ## Find name of .vdi file. New:
   local vdi_file
   vdi_file="$(find "$HOMEVAR/VirtualBox VMs/$VMNAME/"*".vdi")"
   ## example result: "$HOMEVAR"/VirtualBox VMs/whonix-Gateway/whonix-Gateway-disk1.vdi
   ## For debugging it's useful to clone a VM, where only the operating system has been installed,
   ## before running the script or before copying into it.
   ## When restoring the VMClone to VM, the VDI may have another name.

   ## Folder has to exist to mount the image.
   mkdir --parents "$CHROOT_FOLDER"
   $SUDO_TO_ROOT sync

   $SUDO_TO_ROOT guestmount -o allow_other -a "$vdi_file" -m /dev/sda1 "$CHROOT_FOLDER"
   $SUDO_TO_ROOT sync
}

main() {
   root_check
   if [ "$BARE_METAL" = "1" ]; then
      true "${green}INFO: Skipping script, because BARE_METAL=1: $BASH_SOURCE${reset}"
      exit 0
   else
      mount_vdi
   fi
}

main "$@"
