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

   if has guestunmount; 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 -- "${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 "$@"
