#!/bin/bash

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

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

#set -x
set -e

true "INFO: Currently running script: $BASH_SOURCE $@"

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

dist_build_internal_run="true"

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

main() {
   local exit_code
   exit_code=0

   while :
   do
       case $1 in
           --)
               shift
               break
               ;;
           *)
               break
               ;;
       esac
   done

   local unmount_folder
   unmount_folder="$1"

   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 "$unmount_folder" ; then
      true "INFO: Already unmounted after first attempt using --lazy, ok."
      return 0
   fi

   $SUDO_TO_ROOT umount --verbose "$unmount_folder" || { exit_code="$?" ; 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" || { exit_code="$?" ; 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

   echo "ERROR: unmount_folder '$unmount_folder' not unmounted after three attempts!"
   exit 1
}

main "$@"
