#
#  Copyright (c) 2006-2011 Commvault systems, Inc. <http://www.commvault.com>.
#  This file is part of OpenArchive.

#  This file is licensed to you under your choice of the GNU Lesser
#  General Public License, version 1 or any later version (LGPLv3 or
#  later), or the GNU General Public License, version 2 (GPLv2), in all
#  cases as published by the Free Software Foundation.
#
attrib="trusted.openarchive.mtime"
binary=`basename $0`
input_file=""
mnt_path=""
failed_files_path=""

excmd()
{
    command="$*"
    ${command}
    ret=$?
    if [ $ret != 0 ]; then
        echo "Execution of ${command} failed with return code:$ret"
        exit 1
    fi
}

usage()
{
    echo "$binary --input <input file path> --mnt <gluster mount path> --fail <failed_files_path>"
}

parse_args() 
{
    while [ "$1" != "" ]; do
        case $1 in
            --input | -i)     shift
                              input_file=$1
                              ;;

            --mnt | -i)       shift
                              mnt_path=$1
                              ;;

            --fail | -f)      shift
                              failed_files_path=$1
                              ;;

            --help | -h)      usage
                              exit
                              ;;
        esac
        shift
    done
}

validate_params()
{
    if [ -z "$input_file" ]; then
        usage
        exit 1  
    fi

    if [ ! -f "$input_file" ] || [ ! -d "$mnt_path" ]; then
        usage
        exit 1  
    fi 
}

parse_args "$@"
validate_params
echo "" > $failed_files_path

while read entry; do
    #Get the mtime of the file when it was backed up
    full_path="$mnt_path/$entry"
    f_mtime=`sudo getfattr -d -e text -m $attrib $full_path  2>/dev/null | grep $attrib | cut -d '=' -f 2 | tr -d '"'`
    setfattr -n "trusted.glusterfs.csou.complete" -v $f_mtime $full_path
    if [ $? -ne 0 ]; then
        echo $entry >> $failed_files_path
    fi     
done < $input_file
