#!/bin/bash

source /etc/tos/scripts/scripts
script_get_lock > /dev/null
[ $? -ne 0 ] && exit 1

if [ -z "$1" ]; then
    echo -e "usage: $0 [/Volume?]\n"
    script_put_lock > /dev/null
    exit 1
fi

mntpath=$1
FS=`df-json | grep "$mntpath$" | awk '{print $2}'`
if [ "$FS" != "btrfs" ]; then
    echo -e "[$mntpath] filesystem is $FS\n"
    script_put_lock > /dev/null
    exit 1
fi
volume_name=`basename $mntpath`
volume_sort=$(echo $volume_name | tr -cd "[0-9]")
logfile=/tmp/defragment_${volume_name}
touch $logfile

sleep 1
btrfs filesystem defragment -rf $mntpath >/dev/null 2>&1
sleep 1
# send msg to msger...
ter_msg_add -c storage -l info -s notification -k sot_fragmentation_complete -o ${volume_sort}
rm -f $logfile

# all process over
script_put_lock > /dev/null
exit 0
