#!/bin/sh
#
# Andrei.Ryjov@LogicaCMG.COM aka aryzhov@yahoo Fri Feb  6 09:29:05 MET 2004
# CLI VxCreateDataDG for OpForce @ LogicaCMG
#

exec >/dev/console 2>&1
CrashMe() { exec 2>&1; echo ERROR:; echo "$*"; echo Aborted; exit 1; }

#
# This should run in parallel with root disk mirroring, just a bit later,
# so that all resources for rootdg get allocated already.
#
# Do some calculations first
#
AllDisks=`vxdisk list | grep '^c[0-9]*t'`
RootDGDisks=`echo "$AllDisks"      | awk '$4=="rootdg" {print}'`
NotRDGDisks=`echo "$AllDisks"      | awk '$4!="rootdg" {print}'`
AllCTRLs=`echo "$AllDisks"         | cut -dc -f2- | cut -dt -f1 | sort -n | uniq`
RootDGCTRLs=`echo "$RootDGDisks"   | cut -dc -f2- | cut -dt -f1 | sort -n | uniq`
NotRDGCTRLs=`for c in $RootDGCTRLs ; do echo "$AllDisks" | egrep -s "^c${c}t[0-9]*d" || echo $c; done`
DskNPerCTRL=`for c in $AllCTRLs    ; do echo $c \`echo "$AllDisks" | egrep    "^c${c}t[0-9]*d" |  wc -l\` ; done | sort -nr -k2`
FreePerCTRL=`echo "$DskNPerCTRL"   | while read c n ; do echo "$RootDGDisks" | egrep -s "^c${c}t[0-9]*d" && n=\`expr $n - 1\` ; echo $c $n ; done | sort -nr -k2`
MaxDskNPerCTRL=`echo "$DskNPerCTRL"| head -1 | awk '{print $2}'`
#
# Out of two controllers that have maximal number of unalocated disks;
# take one that has less disks; This disk count defines the datadg stripe size.
# We presume all disks have the same size.
#
DataDGStripeDskN=`echo "$FreePerCTRL" | head -2 | tail -1 | awk '{print $2}'`
DataDGCTRLs=`     echo "$FreePerCTRL" | head -2 | awk '{print $1}'`
DataDGDisks=`for c in $DataDGCTRLs ; do echo "$NotRDGDisks" | awk '{print $1}' | egrep "^c${c}t[0-9]*d" | head -$DataDGStripeDskN ; done`
DataDGDisks=`echo "$DataDGDisks" | sort`
#
# Create datadg and init its disks
#
NameDisk() { printf '%02d%02d' `echo $1 | cut -dc -f2- | cut -dt -f1` `echo $1 | cut -dt -f2- | cut -dd -f1`; }

vxdg destroy datadg 2>&-
echo Initializing disks: "\c"
for d in `echo "$DataDGDisks" | cut -ds -f1`; do
  echo " $d ...\c"
  /etc/vx/bin/vxdisksetup -i $d || CrashMe "Failed"
done ; echo done

FirstDisk=`echo "$DataDGDisks" | head -1`
echo Adding disks to datadg: "\c"
echo $FirstDisk ... "\c"
vxdg init datadg dt`NameDisk $FistDisk`=$FirstDisk || CrashMe "Datadg init failed"
for d in `echo "$DataDGDisks" | tail +2` ; do
  echo $d ... "\c"
  vxdg -g datadg adddisk dt`NameDisk $d`=$d || CrashMe "Adding $d to datadg failed"
done
#
#
echo Making a test volume to check maxgrow... "\c"
vxassist -g datadg make data 100m layout=stripe,mirror || CrashMe "Failed"
echo done
SIZE=`set -- \`vxassist maxgrow data\`; while [ $1 != to ] ; do shift; done; echo $2`
vxassist remove volume data || CrashMe "Failed to remove the test volume"
(
  echo Starting creation of data volume len=$SIZE layout=stripe,mirror
  vxassist -g datadg make data $SIZE layout=stripe,mirror || CrashMe "Creation of data volume "
  echo Finished creation of data volume len=$SIZE layout=stripe,mirror
) &
