#!/bin/sh
set -u

op=$1

toolName=`basename $0`
cacheSupportPin=`/bin/get_key_value /etc.defaults/synoinfo.conf cache_support_pin`
tool=synocachepinfiletool
debug=0
debug_log=/var/log/pin-file-ha.log

print()
{
	local msg=$1
	echo "$toolName: $msg"
	if test $debug -eq 1 ; then
		echo "$toolName: $msg" >> $debug_log
	fi
}

if test "$cacheSupportPin" != "yes" ; then
	print "This model doesn't support cache pin file feature"
	exit 0
fi

DoOperation()
{
	local op=$1
	local SupportPin=""
	local fail=0

	if test "$op" == "reload-blocks" ; then
		local volumes=$(grep /volume /etc/fstab | awk '{ printf("%s \n", $2) }')
		for vol in $volumes; do
			SupportPin=`$tool --support-pin --mount-path $vol`

			if test "$SupportPin" = "Yes" ; then
				# Resent the bitmap to driver because it might be clear by the "--unpin-all" command
				$tool --send-bitmap --mount-path $vol

				print  "Do reload blocks on volume $vol"
				$tool --reload-blocks --mount-path $vol
				if test "$?" != "0" ; then
					print "Reload blocks on volume $vol failed"
					fail=1
				else
					print  "Unpin all pin blocks on volume $vol successfully"
				fi
			fi
		done
	elif test "$op" == "unpin-all" ; then
		local caches=$(dmsetup table | grep cachedev | cut -d ":" -f 1)

		for cache in $caches ; do
			SupportPin=`dmsetup table $cache | grep -q "support pin file(1)" && echo Yes`
			if test "$SupportPin" = "Yes" ; then
				print  "Unpin all pin blocks on cache $cache ..."
				$tool --unpin-all --cache-path /dev/mapper/$cache
				if test "$?" != "0" ; then
					print  "Unpin all pin blocks on cache $cache failed"
					fail=1
				else
					print  "Unpin all pin blocks on cache $cache successfully"
				fi
			fi
		done
	else
		print "Unknown op=$op"
		fail=1
	fi

	return $fail
}

if test $debug -eq 1 ; then
	> $debug_log
fi

case "$op" in
	--reload-blocks)
		DoOperation "reload-blocks"
		exit $?
		;;
	--unpin-all)
		DoOperation "unpin-all"
		exit $?
		;;
	*)
		print "Unknwon op = $op"
		exit 1
		;;
esac

