#!/bin/bash

. $(dirname $0)/../../include.rc
. $(dirname $0)/../../cluster.rc
. $(dirname $0)/../../volume.rc

function CLI_1_rebalance_status_field {
        #The rebalance status can be upto 3 words, (ex:'fix-layout in progress'), hence the awk-print $7 thru $9.
        #But if the status is less than 3 words, it also prints the next field i.e the run_time_in_secs.(ex:'completed 3.00').
        #So we trim the numbers out with  `tr`. Finally remove the trailing white spaces with sed. What we get is one of the
        #strings in the 'cli_vol_task_status_str' char array of cli-rpc-ops.c

        $CLI_1 volume rebalance $1 status | awk '{print $7,$8,$9}' |sed -n 3p |tr -d '[^0-9+\.]'|sed 's/ *$//g'
}

function check_peers {
        $CLI_1 peer status | grep 'Peer in Cluster (Connected)' | wc -l
}

function volinfo_field()
{
    local vol=$1;
    local field=$2;

    $CLI_1 volume info $vol | grep "^$field: " | sed 's/.*: //';
}

cleanup;
TEST launch_cluster 2;
TEST $CLI_1 peer probe $H2;

EXPECT_WITHIN $PROBE_TIMEOUT 1 check_peers

$CLI_1 volume create $V0 $H1:$B1/$V0  $H2:$B2/$V0
EXPECT 'Created' volinfo_field $V0 'Status';

$CLI_1 volume start $V0 
EXPECT 'Started' volinfo_field $V0 'Status';

#Mount FUSE
TEST glusterfs -s $H1 --volfile-id=$V0 $M0;

TEST mkdir $M0/dir{1..4};
TEST touch $M0/dir{1..4}/files{1..4};

TEST $CLI_1 volume add-brick $V0 $H1:$B1/${V0}1 $H2:$B2/${V0}1 

TEST $CLI_1 volume rebalance $V0  start 

EXPECT_WITHIN 60 "completed" CLI_1_rebalance_status_field $V0
        
$CLI_2 volume status $V0
EXPECT 'Started' volinfo_field $V0 'Status';

#cleanup;
