#!/bin/bash

#########################################################
# A cron-friendly script to reorder XFS filesystems	#
#########################################################
# By Christopher A. Wadge, 05/24/12			#
#							#
# http://files.tuxhelp.org/scripts/xfs-optimize.sh	#
#							#
# Licensed under the GPL version 3. A copy of the GPL	#
# version 3 is included with this script.  If the file, #
# COPYING, is not included, you can find the GPL 	#
# version 3 at the following URL online:		#
#							#
# http://www.gnu.org/licenses/gpl-3.0.html		#
#########################################################

# This script's name:
PROGRAM_NAME="xfs_optimize.sh"
# Date of last revision:
PROGRAM_DATE="05/24/12"

## VARIABLES ##
# The following are pre-determined variables that are not answered by the script.
#####

XFS_FSR_BIN=/usr/sbin/xfs_fsr
XFS_DB_BIN=/usr/sbin/xfs_db
XFS_LOG_TARGET=/var/log/xfs_optimize.log

## !!! Attention Users: Editing below this line is not advised unless you really know what you're doing.

if [ -e /proc/mdstat ] ; then
  if [ "`cat /proc/mdstat | egrep -c '(check|degraded|_|resync|recovery)'`" -ge "1" ] ; then
	echo "*** Detected non-optimal MD array(s) ***" | tee -a $XFS_LOG_TARGET
	date | tee -a $XFS_LOG_TARGET
        cat /proc/mdstat | tee -a $XFS_LOG_TARGET
	echo "*** Declined to perform XFS reorder ***" | tee -a $XFS_LOG_TARGET
	exit 1
  fi
fi
	echo "*** Optimizing all XFS filesystems ***"
	echo "*** Started `date` ***" >> $XFS_LOG_TARGET
		for xd  in `mount | grep xfs | cut -d " " -f 1` ; do
			echo "Volume $xd (before):" | tee -a $XFS_LOG_TARGET
			ionice -c 3 $XFS_DB_BIN -c frag -r $xd | tee -a $XFS_LOG_TARGET
		done
	ionice -c 3 $XFS_FSR_BIN -v >> $XFS_LOG_TARGET
		for xd  in `mount | grep xfs | cut -d " " -f 1` ; do
			echo "Volume $xd (after):" | tee -a $XFS_LOG_TARGET
			ionice -c 3 $XFS_DB_BIN -c frag -r $xd | tee -a $XFS_LOG_TARGET
		done
	echo "*** Completed `date` ***" >> $XFS_LOG_TARGET
	echo "*** Filesystem optimization complete ***"