#!/bin/sh

PATH=/usr/bin:/usr/sbin

# The following six variables must be configured
BOOT_DISK=c0t0d0
MIRROR_DISK=c0t1d0
ROOT_SLICE=0
SWAP_SLICE=1
METADB_SLICE=3
# Mirror all slices except $METADB_SLICE
SLICES_TO_MIRROR="$ROOT_SLICE $SWAP_SLICE 4 5 6"

# Name of one-time submirror attach script
RC_SCRIPT=/etc/rc2.d/S99submirrorattach

# Copy the partition table of $BOOT_DISK to $MIRROR_DISK
prtvtoc /dev/rdsk/${BOOT_DISK}s2 | fmthard -s - /dev/rdsk/${MIRROR_DISK}s2

# Create DiskSuite state database replicas
metadb -a -f -c2 /dev/dsk/${BOOT_DISK}s${METADB_SLICE} /dev/dsk/${MIRROR_DISK}s${METADB_SLICE}

# Create $RC_SCRIPT
echo "#!/bin/sh" > $RC_SCRIPT

# Mirror all slices in $SLICES_TO_MIRROR
for SLICE in $SLICES_TO_MIRROR
do
   BOOT_DISK_SUBMIRROR=`expr 10 + $SLICE`
   MIRROR_DISK_SUBMIRROR=`expr 20 + $SLICE`
   MIRROR=$SLICE
   metainit -f d${BOOT_DISK_SUBMIRROR} 1 1 ${BOOT_DISK}s${SLICE}
   metainit -f d${MIRROR_DISK_SUBMIRROR} 1 1 ${MIRROR_DISK}s${SLICE}
   metainit -f d${MIRROR} -m d${BOOT_DISK_SUBMIRROR}
   echo "metattach d${MIRROR} d${MIRROR_DISK_SUBMIRROR}" >> $RC_SCRIPT
   if [ "$SLICE" -ne "$ROOT_SLICE" ] ; then
      sed -e "s@/dev/dsk/${BOOT_DISK}s${SLICE}@/dev/md/dsk/d${MIRROR}@" \
         -e "s@/dev/rdsk/${BOOT_DISK}s${SLICE}@/dev/md/rdsk/d${MIRROR}@" \
         /etc/vfstab > /etc/vfstab.new
         mv /etc/vfstab.new /etc/vfstab
   fi
done

# Remove $RC_SCRIPT after execution on next boot
echo "rm $RC_SCRIPT" >> $RC_SCRIPT

# Run metaroot on $ROOT_SLICE
metaroot d${ROOT_SLICE}

# Change crash dump device to use swap metadevice, if applicable
dumpadm -d /dev/md/dsk/d${SWAP_SLICE}

# Create "mirror" device alias for $MIRROR_DISK
MIRROR_DISK_DEVICE_PATH=`ls -l /dev/dsk/${MIRROR_DISK}s${ROOT_SLICE} | \
   perl -ne 'print "$1disk$3" if m!\.\./\.\./devices(.*/)(\w+)(@\d+,\d+:\w+)!'`
eeprom "nvramrc=devalias mirror $MIRROR_DISK_DEVICE_PATH"
eeprom "use-nvramrc?=true"

# Determine boot disk device alias

# Note: bootpath includes the slice at the end
# For matching the boot disk's device alias based on the bootpath, only
# match up to the colon
BOOT_DISK_DEVICE_PATH=`ls -l /dev/dsk/${BOOT_DISK}s${ROOT_SLICE} | \
   perl -ne 'print "$1disk$3" if m!\.\./\.\./devices(.*/)(\w+)(@\d+,\d+):\w+!'`
BOOT_DISK_DEVICE_ALIAS=`prtconf -pv | grep $BOOT_DISK_DEVICE_PATH | \
   awk '{ print $1 }' | grep "^disk" | tail -1 | tr -d ':'`

# Set the eeprom boot-device setting to the device aliases for $BOOT_DISK
# and $MIRROR_DISK. Attempt to boot from the network if both disks fail.
eeprom "boot-device=$BOOT_DISK_DEVICE_ALIAS mirror net"

# Bypass "quorum" rule if the system has only two internal disks
# This will allow the system to boot unattended if one of the disks fails
INTERNAL_DISKS=`format < /dev/null | egrep '[0-9]\. c[0-9]t[0-9]d[0-9]' | wc -l`
if [ "$INTERNAL_DISKS" -eq 2 ] ; then
   echo 'set md:mirrored_root_flag = 1' >> /etc/system
fi
