#!/usr/bin/bash
#
# This script expects pvfs2-xattr and pvfs2-stat to be on your search path.
#

function usage {
    echo "pvfs2-setmattr {-c copies} {-m mode} {-h} -f file"
    echo "  copies : positive numeric value"
    echo "    mode : 100 => No Mirroring"
    echo "           200 => Create Mirror when IMMUTABLE is set"
    echo "      -h : Display this message" 
    echo "    file : file to mirror (may include path)"
    exit
}

if [ "$#" -lt 4 ] || [ "$#" -gt 6 ]
then
  usage
fi

XATTR_PATH=`which pvfs2-xattr 2> /dev/null`
if [ $? -eq "1" ]
then
  echo "pvfs2-xattr command not found."
  exit
fi

MODE=0
COPY=0

while [[ $# -gt 0 ]]
do
  case "$1" in
    -c) COPY=1
        shift
        if [[ "$1" =~ ^[0-9]+$ ]]
        then
          CVAL="$1"
        else
          usage
        fi
        shift;;
    -m) MODE=1
        shift
        if [[ "$1" =~ ^[0-9]+$ && ( "$1" -eq 100 || "$1" -eq 200 ) ]]
        then
          MVAL="$1"
        else
          usage
        fi
        shift;;
    -f) shift
        pvfs2-stat "$1" > /dev/null 2>&1
        if [ "$?" != 0 ]
        then
          usage
        fi
        TARGET="$1"
        shift;;
     *) usage;;
  esac
done

if [ "$COPY" -eq "1" ]
then
     pvfs2-xattr -s -k user.pvfs2.mirror.copies -v "$CVAL" "$TARGET"
fi

if [ "$MODE" -eq "1" ]
then
     pvfs2-xattr -s -k user.pvfs2.mirror.mode -v "$MVAL" "$TARGET"
fi

