#!/bin/bash
##########################################
#
################文件夹更名
#
##########################################

folderid=$1
foldername=$2
db=/etc/base/nasdb

[ -z "$folderid" -o -z "$foldername" ] && exit 1

mntpath=`sqlite3 $db "select mntpath from share where folder_id=$folderid"`
ecryptfs=`sqlite3 $db "select ecryptfs from share where folder_id=$folderid"`

device=`dirname "$mntpath"`
old_foldername=`basename "$mntpath"`

is_running(){
	local exec=$1
	local result=`pidof $exec 2>/dev/null`
	[ ! -z "$result" ] && {
		echo 0
	} || echo 1
}

service_action(){
	local act=$1
	/etc/init.d/samba $1 >/dev/null
	/etc/init.d/nfs $1 >/dev/null
	/etc/init.d/ftp $1 >/dev/null
}

umount_path(){
	local path=$1
	[ -z "$path" ] && return 1
	local num=0
	while [ $num -lt 3 ]; do
		umount -fl "$path"
		df-json | grep "$path" > /dev/null
		[ $? -ne 0 ] && break
		let num=num+1
	done
	# 判断是否umount成功...
	df-json | grep "$path" > /dev/null
	if [ $? -eq 0 ]; then
		return 1
	fi
	local name=`basename "$path"`		
	rm -f "/mnt/${name}"
	rm -fr "$path"
	return 0
}

updatedb(){
	local fname="$1"
	local mntpath="${device}/${fname}"
	sqlite3 $db "update share set foldername='$fname',mntpath='$mntpath' where folder_id=$folderid"
}

if [ $ecryptfs -eq 1 ]; then
	oldpath="${device}/@${old_foldername}@"
	newpath="${device}/@${foldername}@"
	[ -e "$newpath" ] && exit 1
	df-json | grep "$mntpath" > /dev/null
	if [ $? -eq 0 ]; then
		service_action stop
		umount_path "$mntpath"
		if [ $? -eq 0 ]; then
			mv -f "$oldpath" "$newpath"
			updatedb "${foldername}"
			service_action start
		fi
	else
		mv -f "$oldpath" "$newpath"
		updatedb "${foldername}"
	fi
else
	newpath="${device}/${foldername}"
	[ -e "$newpath" ] && exit 1
	[ ! -z "${old_foldername}" ] && rm -fr "/mnt/${old_foldername}"	
	mv -f "$mntpath" "$newpath"
	updatedb "${foldername}"
	mdname=`basename $device`
	ln -fsn "$mdname/${foldername}" "/mnt/${foldername}"
	[ `is_running "smbd"` -eq 0 ] && /etc/init.d/samba restart > /dev/null
	[ `is_running "rpcbind"` -eq 0 ] && /etc/init.d/nfs restart > /dev/null
	[ `is_running "smbftpd"` -eq 0 ] && /etc/init.d/ftp restart > /dev/null
fi

exit 0