#!/bin/ksh
#
# XARY aka Andrei.Ryjov@spasu.net Tue Oct  7 07:26:39 CEST 2008
#
# check if $RESERVE gb is too large so rthat we can give up some LUNs
#
uname -s | egrep -s AIX || exit 0       # Run on AIX only

TODAY=`date +%Y%m%d`
LASTRUNFILE=/var/tmp/`basename $0`.lastrun
touch $LASTRUNFILE
[ x"`cat $LASTRUNFILE`" = x"$TODAY" ] && exit 0 # Reduce the noise bu running once a day only
echo $TODAY >$LASTRUNFILE


DEFAULT_THRESHOLD=299 # gigabytes
HOSTNAME=`uname -n`
#
# Some groups may have different $RESERVE threshold
#
EXCEPTIONS="



"

RC=0 # Return Code

for i in `lsvg -L`; do
  #
  # See if the group is in exception list
  # Try mo match the hostname + vgname first (highest priority),
  # then try wildcard+vgname, and then fallback to default
  #
  NEW_THRESHOLD=`echo "$EXCEPTIONS" | awk '$1=="'$HOSTNAME'" && $2=="'$i'" {print $3}' | tail -1`
  echo $NEW_THRESHOLD | egrep -s '^[0-9]+$' || NEW_THRESHOLD=`echo "$EXCEPTIONS" | awk '$1=="*" && $2=="'$i'" {print $3}' | tail -1`
  echo $NEW_THRESHOLD | egrep -s '^[0-9]+$' || NEW_THRESHOLD=$DEFAULT_THRESHOLD
  CURRENT_RESERVE=`lsvg -L $i | awk '/FREE/ {print $(NF-1)}' | sed 's/(//' | awk '{printf("%d", $1/1024)}'`

  #
  # Make sure that all volumes in the group have the same PP per LV ratio,
  # and divide $CURRENT_RESERVE by it
  # (for instance, mirrored VGs  need double reserve)
  #
  R=`for v in \`lsvg -lL $i | awk '$NF~/\// {print $1}'\`; do
    lslv -L \$v | awk '/^LPs:/ {print $4/$2}'
  done | sort -u`

  [ `echo $R | wc -w` -gt 1 ] && {
    printf "`uname -n` VG $i not fully mirrored\n"
    RC=1
  }

  R=`echo \`echo "$R" | head -1\``

  echo $R | egrep -s '[0-9]' && CURRENT_RESERVE=`expr $CURRENT_RESERVE / $R`

  #
  # Now, finally, check if we are below the threshol
  #

  [ $CURRENT_RESERVE -gt $NEW_THRESHOLD ] && {
    RC=1
    MESSAGE="$MESSAGE\n`printf \"%-10s %10d gb left\" $i $CURRENT_RESERVE"
  }
done

[ $RC -eq 0 ] && exit 0


printf "Disk space reserve above $NEW_THRESHOLD - give up some\n\n$MESSAGE\n"
exit $RC
