#!/bin/sh

if [ -z "$1" ]; then
    echo "error: Need to specify umount dir"
    echo "example: rfue-umount /mnt/ex"
    exit 1
fi

init()
{
    if uname -s 2>/dev/null 1>/dev/null; then
        TOS="`uname -s`"
    else
        if echo $OSTYPE | grep darwin >/dev/null; then
            TOS="Darwin"
        elif cat /proc/version | grep Linux 2>/dev/null 1>/dev/null; then
            TOS="Linux"
        fi
    fi

    if [ "$TOS" = "Darwin" ]; then
        OS=macosx
        if uname 2>/dev/null -m | grep iPhone >/dev/null 2>/dev/null; then
           OS=iphoneos
        fi
    elif [ "$TOS" = "Linux" ]; then
        OS=linux
    elif [ "$TOS" = "FreeBSD" ]; then
        OS=freebsd
    elif echo "$TOS" | grep "_NT" >/dev/null; then
        OS=windows
    else
        echo "error: unsupported os: $TOS, Please tell us to fix"
        exit 1
    fi

    sudoprefix=
    if id -u 2>/dev/null 1>/dev/null; then
        if ! id | grep "uid=0(" 2>/dev/null 1>/dev/null; then
            if sudo -V >/dev/null 2>&1; then
                sudoprefix=sudo
            else
                echo "Warning: You need to run the script with root privileges"
            fi
        fi
    fi
}

init
$sudoprefix lsof +d $1 2>/dev/null | awk '{print $2}' | sort | uniq | xargs $sudoprefix kill -9 2>/dev/null
if [ $OS = "linux" ]; then
   pid=$(ps afx | grep -v grep | grep -v rfue-umount.sh | grep "rfue" | grep "${1%*/}" | awk '{print $1}')
   if [ -n "$pid" ]; then
      $sudoprefix kill $pid
      echo "umount [$1] OK"
   else 
      echo "error: [$1] not mounted"
   fi
elif [ "$OS" = "macosx" ]; then
   $sudoprefix umount $1
fi

