
DST="$1"
ext="$2"
timestamp="$3"
NDAYS="$4"

# check for global directory structure

if ! test -d "$DST"
then
   echo "creating $DST"
   if ! mkdir "$DST"
   then
      echo "failed to create $DST"
      exit 1
   fi
fi

if ! test -d "$DST/data"
then
   echo "creating $DST/data"
   if ! mkdir "$DST/data"
   then
      echo "failed to create $DST/data"
      exit 1
   fi
fi

if ! test -d "$DST/xattr"
then
   echo "creating $DST/xattr"
   if ! mkdir "$DST/xattr"
   then
      echo "failed to create $DST/xattr"
      exit 1
   fi
fi

if ! test -d "$DST/archive"
then
   echo "creating $DST/archive"
   if ! mkdir "$DST/archive"
   then
      echo "failed to create $DST/archive"
      exit 1
   fi
fi

# check for local directory structure

if ! test -d "$DST/data/$ext"
then
   echo "creating directory $DST/data/$ext"
   if ! mkdir -p "$DST/data/$ext"
   then
      echo "failed to create directory $DST/data/$ext"
      exit 1
   fi
fi

if ! test -d "$DST/xattr/$ext"
then
   echo "creating directory $DST/xattr/$ext"
   if ! mkdir -p "$DST/xattr/$ext"
   then
      echo "failed to create directory $DST/xattr/$ext"
      exit 1
   fi
fi


if test "$NDAYS" '!=' '-'
then

   # remove old backups
   
   ( cd "$DST/archive" && find . \! -name '.' -prune -name 'arch.*' -mtime "+$NDAYS" -exec rm -rf {} \; )
   
   # create backup directory structure
   
   if ! mkdir "$DST/archive/arch.$timestamp"
   then
      echo "failed to create $DST/archive/arch.$timestamp"
      exit 1
   fi
   
fi

exit 0
