#!/usr/bin/ksh

#       Procedure to replace a mirror
#       Bill Sherman - June 1, 1999

DEBUG=  #echo

#       Source in the global variables
#     These are kept in a cluster.variables file

DISK1=/dev/dsk/c0t0d0
DISK2=/dev/dsk/c2t4d0

ROOT=s0
SWAP=s1
META=s3
BTO=s4
VAR=s5
LENSDATA=s6

#     End of cluster.variables

#       Minimize the PATH stuff
PATH=/sbin:/usr/sbin:/bin:/usr/sbin:/usr/opt/SUNWmd/sbin
export PATH

BADFILE=/tmp/bad_mirror.lis

#       Get a list of the bad partitions
metastat | awk '
        BEGIN { MIR = ""; MD = ""; STATE = ""; DEV = "" }
        /^d.*:/ { 
                if ( MD > "" && STATE !~ /Okay/ ) { 
                        print MIR, MD, DEV 
                        MIR = ""
                        MD = ""
                        STATE = ""
                        DEV = ""
                }
                if ( $0 ~ /Mirror/ ) { MIR = substr( $1, 1, length( $1)
- 1) }
                else { MD = substr( $1, 1, length( $1) - 1) }
        }
        /State:/ { STATE = $2 }
        /^[     ]c/ { DEV = $1 }
END { if ( MD > "" && STATE !~ /Okay/ ) { print MIR, MD, DEV }
}' >$BADFILE

DISK=$( awk '{print substr( $NF, 1, length( $NF) - 2) }' $BADFILE | sort
-u )
if [[ -z $DISK ]]
then
   echo "No disk to replace... exiting"
   exit 1
fi

#       Remove the metaDB from the bad disk
echo "Removing the MetaDB from ${DISK}..."
${DEBUG} metadb -d ${DISK}${META}

#       Remove the entries in /dev/dsk and /dev/rdsk
${DEBUG} rm /dev/dsk/${DISK}s? /dev/rdsk/${DISK}s?

#       Physically replace the disk
read ans?"Replace the bad drive now. Press <RETURN> to continue "

#       Wait for the disk to spin up
WAIT=20
L=0
printf "Waiting ${WAIT} seconds for the drive to spin up"
while [[ ${L} -lt ${WAIT} ]]
do
   printf "."
   sleep 1
   let "L = ${L} + 1"
done
print

#       Reconfigure the drivers and disk entries
echo "Reconfiguring and formatting the disk..."
${DEBUG} /usr/sbin/drvconfig
${DEBUG} /usr/sbin/disks

#       Format the new drive
if [[ -r /HA/HADISK.format && -r /HA/HADISK.commands ]]
then
   export FORMAT_PATH=/HA/HADISK.format:/etc/format.dat
   ${DEBUG} format -d ${DISK} -f /HA/HADISK.commands -p HADISK
else
   echo "Can't find files for formatting disk... exiting!"
   exit 1
fi

#       Recreate the metaDB
echo "Recreating the MetaDB..."
${DEBUG} metadb -c 3 -a ${DISK}${META}

#       Tell DiskSuite to replace the mirrors
echo "Reattaching the mirrors..."
cat $BADFILE | while read MIR MD DEV
do
   ${DEBUG} metareplace -e  ${MIR} ${DEV}
done

cat <<EOF

The disk should now be synchronizing.  Use the stat command
to check the status.  

EOF
rm ${BADFILE}
stat
exit
