#!/bin/bash

## Copyright (C) 2012 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

set -x
set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit

true "INFO: Currently running script: ${BASH_SOURCE[0]} $*"

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/variables"

exception_handler_unmount-vdi-force() {
   : printf '%s\n' "
${red}${bold}BASH_COMMAND${reset}: $BASH_COMMAND
${red}${bold}ERROR ${BASH_SOURCE[0]}: | 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.
   rmdir -r -- "$CHROOT_FOLDER" || true
   sync || true
}

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

main "$@"
