#!/bin/bash

## Copyright (C) 2012 - 2025 ENCRYPTED SUPPORT LLC <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"

## XXX: hardcoded path
source "$HOME/derivative-maker/help-steps/pre"
source "$HOME/derivative-maker/help-steps/colors"
source "$HOME/derivative-maker/help-steps/variables"

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

unmount_vdi() {
   trap "exception_handler_unmount-vdi" ERR INT TERM

   sync

   local command_v_exit_code="0"
   command -v guestunmount >/dev/null || { command_v_exit_code="$?" ; true; };

   if [ "$command_v_exit_code" = "0" ]; then
      true "${bold}${cyan}INFO: guestunmount available, using it, ok... ${reset}"
      guestunmount "$CHROOT_FOLDER"
   else
      ## guestunmount is not available in Debian Wheezy. Only since Debian Jessie.
      true "${bold}${cyan}INFO: guestunmount not available, using \"fusermount -u\" instead, ok... ${reset}"
      fusermount -u "$CHROOT_FOLDER"
   fi
   sync

   ## Delete temporary folder.
   ## It did not contain anything. It was only a mount point.
   rm -r "$CHROOT_FOLDER"
   sync
}

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

main "$@"
