#!/bin/ksh
#
# Usage : filehist
#
#	Shell script will process required environment variables and 
#	analyze GPFS filesystems which are mounted
#

PATH=/tmp/mmfs:/usr/lpp/mmfs/bin:/usr/lpp/mmfs/samples/util:/usr/lpp/mmfs/samples/debugtools:/usr/sbin:/bin:$PATH
#check for required commands
if ! which tsinode 1>/dev/null
then
  print "filehist: tsinode not found. Run 'make tsinode' in /usr/lpp/mmfs/samples/util"
  return 1
fi
if ! which tsfilehist.awk 1>/dev/null
then
  print "filehist: /usr/lpp/mmfs/samples/debugtools/tsfilehist.awk not found"
  return 2
fi

#get mount points for GPFS filesystems
opsys=$(uname -s)
if [[ $opsys = AIX ]]; then
  mtpts=$(mount|awk '$3 == "mmfs" {print $2":"substr($1,6)}')
elif [[ $opsys = Linux ]]; then
  mtpts=$(mount|awk '$5 == "gpfs" {print $3":"substr($1,6)}')
else
  print "$opsys not AIX or Linux"
  return 1
fi
echo "Getting file histogram for: $mtpts"

#get free space, blocksize of the filesystem, and nsd's
for mf in $mtpts; do
  mp=${mf%:*}; fs=${mf#*:}
  df=$(df -k $mp | tail -1 | awk '{print $2 "k"}')
  blksz=$(tslsfs $fs -B | tail -1 | awk '{print $2/1024}')
  diskls="$(tslsdisk $fs -i 2>/dev/null)"
  integer disks=$(echo "$diskls"| wc -l)
  let bk=disks
  let bk4m=4096/blksz
  [[ $bk -lt $bk4m ]] && bk=$bk4m
  [[ $bk -lt 100 ]] && bk=100
  echo "Writing output to $fs.filesum "
  echo "=======================\n$fs: $(hostname) $(date)\n=======================\n" > $fs.filesum
  df -k $mp >> $fs.filesum
  echo "\n" >> $fs.filesum
  mmlsfs $fs >> $fs.filesum
  echo "\n\n$diskls\n\n" >> $fs.filesum
  echo "Background: tsinode $mp | tsfilehist.awk availablespace=$df nbuckets=$bk blocksize=$blksz"
  tsinode $mp | tsfilehist.awk availablespace=$df nbuckets=$bk blocksize=$blksz >> $fs.filesum &

done
echo "Waiting for background processes to complete"
wait
