#!/bin/bash

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

## syntax:
## unmount-helper -- /path/to/folder

#set -x
set -o errexit
set -o nounset
set -o pipefail
set -o errtrace

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

MYDIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" && pwd )"

dist_build_source_run="true"

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

main() {
   while :
   do
       case "${1:-}" in
           --)
               shift
               break
               ;;
           *)
               break
               ;;
       esac
   done

   local unmount_folder
   unmount_folder="${1:-}"
   if [ -z "$unmount_folder" ]; then
      printf '%s\n' "$0: ERROR: unmount_folder argument missing." >&2
      exit 1
   fi

   sync

   ## kill gpg-agent
   $SUDO_TO_ROOT "$MYDIR/umount_kill.sh" "$unmount_folder"

   if ! $SUDO_TO_ROOT mountpoint --quiet -- "$unmount_folder" ; then
      true "INFO: Not mounted, no need to unmount, ok."
      return 0
   fi

   sync
   ## Sleep to work around some obscure bug.
   ## http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=734794
   ## Could also try as a workaround:
   ## dmsetup ls
   ## dmsetup remove $device
   ##sleep 6 &
   #wait "$!"
   #sync

   ## Debugging.
   #$SUDO_TO_ROOT cat -- /proc/mounts
   #$SUDO_TO_ROOT dmsetup ls
   #$SUDO_TO_ROOT losetup --all

   $SUDO_TO_ROOT umount --verbose --lazy "$unmount_folder" || true "INFO: 'umount --verbose --lazy unmount_folder' non-zero exit code."
   sync
   #sleep 6

   if ! $SUDO_TO_ROOT cat -- /proc/mounts | grep --fixed-strings -- "$unmount_folder" ; then
      true "INFO: Already unmounted after first attempt using --lazy, ok."
      return 0
   fi

   $SUDO_TO_ROOT umount --verbose "$unmount_folder" || true "INFO: 'umount --verbose $unmount_folder' non-zero exit code."
   sync
   #sleep 6

   if ! $SUDO_TO_ROOT mountpoint --quiet -- "$unmount_folder" ; then
      true "INFO: Already unmounted after second attempt using normal mount, ok."
      return 0
   fi

   $SUDO_TO_ROOT umount --verbose --force -- "$unmount_folder" || true "INFO: umount '--verbose --force $unmount_folder' non-zero exit code."
   sync
   #sleep 6

   if ! $SUDO_TO_ROOT mountpoint --quiet -- "$unmount_folder" ; then
      true "INFO: Already unmounted after third attempt using --force, ok."
      return 0
   fi

   sync

   ## Debugging.
   $SUDO_TO_ROOT cat -- /proc/mounts

   printf '%s\n' "ERROR: unmount_folder '$unmount_folder' not unmounted after three attempts!"
   exit 1
}

main "$@"
