#!/bin/bash

# This is the 'mover' script used for moving files from the cache disk to the
# main array.  It is typically invoked via cron.

# After checking if it's valid for this script to run, we check each of the top-level
# directories on the cache disk: if the directory also already exists in the array, then we
# use the 'find' command to process the objects (files and directories) of that directory.
# Note that files at the top level of the cache disk are never copied to the array.

# The script is set up so that hidden directories (i.e., directory names beginning with a '.'
# character) at the topmost level of the cache drive are also not copied to the user share file
# system. This behavior can be turned off by uncommenting the following line:
# shopt -s dotglob

# The 'find' command generates a list of all files and directories on the cache disk.
# For each file, if the file is not "in use" by any process (as detected by 'fuser' command),
# then the file is copied to the array, and upon success, deleted from the cache disk.
# For each directory, if the directory is empty, then the directory is created on the array,
# and upon success, deleted from the cache disk.

# For each file or directory, we use 'rsync' to copy the file or directory to the array.
# We specify the proper options to rsync so that files and directories get copied to the
# array while preserving ownership, permissions, access timess, and extended attributes (this
# is why we use rsync: a simple mv command will not preserve all metadata properly).

# Only run script if cache disk enabled and in use
if [ ! -d /mnt/cache -o ! -d /mnt/user0 ]; then
  exit 0
fi

# If a previous invokation of this script is already running, exit
if [ -f /var/run/mover.pid ]; then
  if ps h `cat /var/run/mover.pid` | grep mover ; then
      echo "mover already running"
      exit 0
  fi
fi
echo $$ >/var/run/mover.pid
echo "mover started"

cd /mnt/cache

for Share in */ ; do
  if [ -d "/mnt/user0/$Share" ]; then
    echo "moving $Share"
    find "./$Share" -depth \( \( -type f ! -exec fuser -s {} \; \) -o \( -type d -empty \) \) -print \
      -exec rsync -i -dIWRpEAXogt --numeric-ids --inplace {} /mnt/user0/ \; -delete
  else
    echo "skipping $Share"
  fi
done

rm /var/run/mover.pid
echo "mover finished"
