#!/bin/sh
#Unmount filesystem from AUFS
#VERSION 4.4

if [ -f $(dirname $0)/pfs ] ;  then
    . $(dirname $0)/pfs
else 
    . $(which pfs) || exit 13 
fi    

HLP () {
  echo "Usage: $(basename "$0") FYLESYSTEM (squashfs module, dir, iso, img, etc) or layer number (see aufs-n)"
  echo "-n  --no-update  - do not update icon caches, fonts, etc"
  echo "-s  --saveram    - do not remove module from RAM after unmounting" 
  echo "-v               - verbose output" 
  echo "-h  --help       - this help"
  exit 2
}

for arg in "$@"
do
  case "${arg}" in
    "-n" | "--no-update") fupdate="no";;
    "-s" | "--saveram") saveram="yes";;
    "-v") verb="yes";;
    "-h" | "--help") infile=""; break;;
    "-"*[A-Za-z]*) echo "$(basename "$0"): invalid option -- '$(echo ${arg} | tr -d '-')'" >&2; exit 1;;
    *) infile="${arg}";;
  esac
done

[ "${infile}_" = "_" ] && HLP

allow_only_root

if [ -f "${infile}" ] ; then 
	findit="[[:punct:]]$(basename "$(realpath "${infile}")" )$"
elif [ "$(echo "$infile" | sed 's/^[[:digit:]].$/digit/')" = "digit" ] ; then 
	findit="^$infile#"
else
	findit="[[:punct:]]$(basename "${infile%.$EXT}").${EXT}$"
fi
#echo --$findit
#mountpoint="${prefixmp}${fsname}"
#mountpoint="$(awk  '{print $2}' /proc/mounts | grep  "${fsname}" )"
mountpoint=$(aufs-n --hidetop --raw '$n#$bundle' |grep "$findit" |awk -F# '{print $2}' )
if [ -d "${mountpoint}" ]; then
  sync
  mountb -t aufs -o remount,del:"${mountpoint}"/ aufs /  2>/dev/null
  stataufs=$?
  sync
 UP(){
  if [ "${fupdate}" != "no" -a ${stataufs} -eq 0 ] ; then
	  pfs_update_caches "${mountpoint}" 
	for script in $(find $(dirname $0) -maxdepth 1 -name "runpfsunload*" -user root) ; do 
	  $script "${mountpoint}"  & 
	done
  fi
 }
  losetupb |grep -q "${copyramdir}${fsname}"  && ramfree=yes 
  UP && umountb -d "${mountpoint}" 2>/dev/null 
  status=$?
  sync
  rmdir "${mountpoint}" >/dev/null
  [ ${status} -eq 0 ] && status=${stataufs}
  [ ${status} -gt 0 ] && echo "Unmount \"${fsname}\" failed!" >&2
  sync
else
  echo "Object \"${fsname}\" not mounted." >&2
  status=22
fi
if 	[ $ramfree ] ; then
	[ $saveram ] || pfsramfree "${fsname}" 
fi


if [ "$status" -ne 0 -a "$status" -ne 22 ] ;then
  [ "$verb" ] && for a in $( lsof / |awk '{print $9}' |grep "\/..*" | egrep -v "/proc|/sys|/run|/tmp|/dev|/home" | sort -u) ; do
    [ -f "$a" ] || continue
    [ -d "$a" ] && continue
    [ -f  "$mountpoint/$a"	] && FILES="$FILES $a"
  done
fi

if [ "$FILES" ] ; then 
  echo '' ; echo "Files opened from $1:"
    for f in $FILES ; do 
    echo -n $f 
  [ -f  "$changesDir/$f" ] && echo " - changed" || echo '' 
  done
fi

exit ${status}
