#!/bin/bash

if [ "$#" -ne 3 ]; then
	echo "Usage : $0 <path-to-brick> <volname> replicate"
	exit 1
fi

function gf_gfid_xattr_to_str {
        xval=$1
        echo "${xval:2:8}-${xval:10:4}-${xval:14:4}-${xval:18:4}-${xval:22:12}"
}

function get_random_gfid {
        echo "0x"$(uuidgen | awk -F '-' 'BEGIN {OFS=""} {print $1,$2,$3,$4,$5}')
}

brick=$(echo $1 | sed -e 's,/$,,')

if [ "$3" != "replicate" ]; then
        echo "Invalid volume type"
        exit 1
fi

if [ $3 == "replicate" ]; then
        xattr_type="trusted.afr.*"
        compare_str="0x000000000000000000000000"
fi

xattrop_files=$(ls -lat $brick/.glusterfs/indices/xattrop/ | grep xattrop-)
if [ -z "$xattrop_file" ]; then
        latest_xattrop_file=$brick/.glusterfs/indices/xattrop/xattrop-$(gf_gfid_xattr_to_str $(get_random_gfid))
        touch $latest_xattrop_file
else
        # in case there are more than one xattrop files and cleanup has not been done
        latest_xattrop_file=$($brick/.glusterfs/indices/xattrop/$(echo -e "$xattrop_files" | tr -s ' ' | cut -d " " -f 9 | sed -n 1p))
fi
pseudo_xattrop_file=$brick/.glusterfs/indices/xattrop/xattrop-$(gf_gfid_xattr_to_str $(get_random_gfid))
ln $latest_xattrop_file $pseudo_xattrop_file

find $brick -path $brick/.glusterfs -prune -o -path $brick/.trashcan -prune -o -print | while read fpath; do
        # get all xattr output for the file in question
	xattr_output=$(getfattr -m. -de hex $fpath)
        # get gfid of the file
        gfid=$(gf_gfid_xattr_to_str $(echo -e "$xattr_output" | grep trusted.gfid | cut -d = -f 2))

        # for each trusted.afr.* or trusted.ec.dirty xattr, check if non-zero
        echo -e "$xattr_output" | grep $xattr_type | while read xattr; do
                xattr_value=$(echo $xattr | cut -d = -f 2)
                if [ "$xattr_value" ]; then
                        if [ "$xattr_value" != "$compare_str" ]; then
                                        ln $latest_xattrop_file "$brick"/.glusterfs/indices/xattrop/"$gfid"
                                        break;
                        fi
                fi
        done
done

rm -f $pseudo_xattrop_file
