#!/bin/sh
#Unmount filesystem from AUFS
#VERSION 3.6
. $(which pfs)
allow_only_root

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

if [ -f "${infile}" ] ; then 
	fsname="$(basename $(realpath "${infile}"))" 
	checksfsxzb >/dev/null || exitmsg "Kernel not support PFS!" 3
else
	fsname="$(basename "${infile}")"
fi

mountpoint="${prefixmp}${fsname}"
if [ -d "${mountpoint}" ]; then
  sync
  mountb -t aufs -o remount,del:"${mountpoint}"/ aufs / #>/dev/null 2>&1
  stataufs=$?
  sync
  if [ "${fupdate}" != "no" -a ${stataufs} -eq 0 ] ; then
	  pfs_update_caches "${mountpoint}"
	for script in $(ls $(dirname $0)/runpfsunload-*) ; do 
	  $script "${mountpoint}" &
	done
  fi
  
  losetupb |grep -q "${copyramdir}${fsname}"  && ramfree=yes 
  umountb -d "${mountpoint}" #>/dev/null 2>&1
  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=1
fi
if 	[ $ramfree ] ; then
	[ $saveram ] || pfsramfree "${fsname}" 
fi
exit ${status}
