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

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

unmount_vdi_force() {
   trap "exception_handler_unmount-vdi-force" ERR INT TERM

   sync || true

   "$MYDIR"/unprevent-daemons-from-starting || true
   "$MYDIR"/unchroot-raw || true

   ## Will be called if there is an error.
   ## || true to avoid more errors and to ensure
   ## clean unmount.

   sync || true

   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" || true
   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" || true
   fi
   sync

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

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

main "$@"
