#/bin/bash

#set all cache device to readonly

VERSION="1.0.0"
UNAME=`uname -r`
STORE_PATH=/lib/modules/$UNAME/kernel/drivers/md/binlogdev/
if [[ ! -d $STORE_PATH ]]; then
    STORE_PATH=/lib/modules/$UNAME/extra/binlogdev/
fi
BINLOG_PREFIX="/sys/module/binlogdev/holders/cachedev"
BINLOG_INDEX_FILE="/usr/local/ucloud/binlog/idx"

OLD_IFS="$IFS"
IFS=$'\x0A'
for device_info in `cat $BINLOG_PREFIX/0_0/cache_device | grep normal`
do
	name=`echo $device_info | awk '{print $1}'`
	echo "setro $name" > $BINLOG_PREFIX/0_0/cache_device
done

sleep 3
#plugout all cache device
has_dirty_data=1
while [[ $has_dirty_data -eq 1 ]]
do
	has_dirty_data=0
	for device_info in `cat $BINLOG_PREFIX/0_0/cache_device | grep readonly`
	do
		name=`echo $device_info | awk '{print $1}'`
		valid_block=`echo $device_info | awk '{print $5}'`
		next_free_block=`echo $device_info | awk '{print $6}'`
		if [[ $valid_block -eq $next_free_block ]];then
			echo "plugout $name" > $BINLOG_PREFIX/0_0/cache_device
			echo "plugout cache device :$name"
		else
			has_dirty_data=1
			echo "cache device: $name has dirty data $valid_block $next_free_block, please waiting" 
			sleep 10
			continue;
		fi
	done
done
IFS=$OLD_IFS

echo "All cache devices are plugout"
echo "Update cachedev.ko now"
rmmod cachedev

mod=`lsmod |grep cachedev`
if [[ $mod ]]; then
	echo "rmmod cachedev faild"
	exit
fi

rm -f $BINLOG_INDEX_FILE 

cp -f cachedev.ko $STORE_PATH
fallocate -l 100G $BINLOG_INDEX_FILE
modprobe cachedev force_create=1
echo "Update cachedev.ko success"
echo "plugin local /dev/sdc 800000" > /sys/module/binlogdev/holders/cachedev/0_0/cache_device
echo "plugin local cache device success"
cp -f shell/binlog-autolimit.sh ~/autolimit/
cp -f etc/init.d/binlogdev /etc/init.d/binlogdev

