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

source "$MYDIR/pre"
source "$MYDIR/colors"
source "$MYDIR/variables"

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

unmount_raw() {
   trap "exception_handler_unmount-raw" ERR INT TERM

   if [ "$mount_folder" = "" ]; then
      true
   else
      ## hack for help-steps/analyze-image
      CHROOT_FOLDER="$mount_folder"
   fi

   sync

   ## Debugging.
   $SUDO_TO_ROOT losetup --all

   if [ "$kpartx_only" = "true" ]; then
      true "INFO: kpartx_only=$kpartx_only, skipping unmount $CHROOT_FOLDER"
   else
      "$dist_source_help_steps_folder/unmount-helper" "$CHROOT_FOLDER"
   fi

   if [ "$dist_build_mount_raw_file" = "" ]; then
      local img="$binary_image_raw_file"
   else
      local img="$dist_build_mount_raw_file"
   fi

   ## Sleep to work around some obscure bug.
   ## http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=734794
   sleep 2 &
   wait "$!"
   sync

   ## Debugging.
   $SUDO_TO_ROOT losetup --all
   sync

   $SUDO_TO_ROOT kpartx -d -s -v "$img"
   sync

   ## Debugging.
   $SUDO_TO_ROOT losetup --all
   sync

   if [ "$kpartx_only" = "true" ]; then
      true "INFO: kpartx_only=$kpartx_only, skipping debugging: ls -la $CHROOT_FOLDER"
   else
      if test -d "$CHROOT_FOLDER" ; then
         ls -la "$CHROOT_FOLDER"
      else
         true "INFO: CHROOT_FOLDER is not a directory. Perhaps already unmounted?"
      fi
   fi

   if [ "$kpartx_only" = "true" ]; then
      true "INFO: kpartx_only=$kpartx_only, skipping rmdir."
   else
      ## Delete temporary folder.
      ## It did not contain anything. It was only a mount point.
      $SUDO_TO_ROOT rmdir "$CHROOT_FOLDER" || true
      sync
   fi
}

main() {
   if [ "$dist_build_install_to_root" = "true" ]; then
      true "${green}INFO: Skipping script, because dist_build_install_to_root is not set to true: $BASH_SOURCE${reset}"
      exit 0
   else
      unmount_raw
   fi
}

main "$@"
