#!/bin/sh
#Unmount filesystem to AUFS (for PuppyRus) by Zay.
#Version 0.13
#Modify 20.10.2013
#mnt="/mnt/."
#porteus-initrd
mnt="/mnt/live/memory/images/"

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

[ -f "${infile}" ] && fsname="`basename $(realpath "${infile}")`" || fsname="$(basename "${infile}")"
if [ "$(echo "${fsname}" | sed 's/^.*\.//')" = "pfs" ]; then
  checksfsxz >/dev/null 2>&1
  if [ $? -gt 0 ]; then
    echo "Kernel not support PFS!"; exit 1
  fi
fi

mountpoint="$mnt${fsname}"
if [ -d "${mountpoint}" ]; then
  sync
  busybox mount -t aufs -o remount,del:"${mountpoint}"/ aufs / >/dev/null 2>&1
  stataufs=$?
  sync
  if [ "${fupdate}" != "no" ]; then
    if [ ${stataufs} -eq 0 ]; then 
###sfs      [ "$(find "${mountpoint}/lib/modules" "${mountpoint}/usr/lib/modules" -name "*.ko" 2>/dev/null)" != "" ] && depmod &
        m="$(find "${mountpoint}/lib/modules" "${mountpoint}/usr/lib/modules" -type f -name "*.ko" 2>/dev/null)" 
	if [ "$m" ] ;then
	    (for i in $m ; do echo "unload $i" && modprobe -r "`basename "$i" .ko`" ;done && depmod ) &
	fi
###sfs)
###sfs      [ "$(find "${mountpoint}/lib" "${mountpoint}/usr/lib" "${mountpoint}/usr/local/lib" "${mountpoint}/usr/X11R7/lib" -name "*.so" 2>/dev/null)" != "" ] && ldconfig &
      [ "$(find "${mountpoint}/lib" "${mountpoint}/usr/lib" "${mountpoint}/usr/local/lib" "${mountpoint}/usr/X11R7/lib" -type -f -name "*.so" 2>/dev/null)" != "" ] && ldconfig &
      [ -d "${mountpoint}/usr/share/glib-2.0/schemas/" ] && glib-compile-schemas /usr/share/glib-2.0/schemas/ &
###sfs(
        dt="$(find "${mountpoint}/usr/share/applications" "${mountpoint}/usr/local/share/applications" -type f -name "*.desktop" 2>/dev/null)"
	if [ "$dt" ] ;then
	    for i in $dt ;do
		f="$(echo "$i" |sed 's#'"$mountpoint"'##')"
		[ -f "$f" ] && rm "$f" &
	    done
	fi
###sfs)
    fi
  fi
  m="`busybox umount -d "${mountpoint}" 2>&1`"
  status=$?
  sync
  rmdir "${mountpoint}" 2>/dev/null
  [ ${status} -eq 0 ] && status=${stataufs} && `which sudo` rm "/mnt/live/memory/copy2ram/${fsname}" ###sfs
  [ ${status} -gt 0 ] && echo "Unmount \"${fsname}\" failed! \n$m"
  sync
else
  echo "Object \"${fsname}\" not mounted." && exit 1 ###sfs
fi

exit ${status}
