#!/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
shopt -s shift_verbose
export LC_ALL=C

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"
# shellcheck source=../../../helper-scripts/usr/libexec/helper-scripts/has.bsh
source "${HELPER_SCRIPTS_PATH:-}"/usr/libexec/helper-scripts/has.bsh

exception_handler_unmount_vdi() {
   : printf '%s\n' "
${red}${bold}BASH_COMMAND${reset}: ${BASH_COMMAND}
${red}${bold}ERROR ${BASH_SOURCE[0]}: | caller: $(caller)${reset}
"
   exit 1
}

unmount_vdi() {
   trap "exception_handler_unmount_vdi" ERR INT TERM

   sync

   if has guestunmount; 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.
   rmdir -- "${CHROOT_FOLDER}"
   sync
}

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

main "$@"
