#!/usr/bin/sh
#
#
#
# Creating clone disk using disksuite utils
#
# version 1.1 2009.04.27
# jsn & ikorolev
#
# Edit vital parameters here: 
#

ROOT=c0t0d0
CLONE=c0t1d0
rootvol=${CLONE}s0


# Metadevices to sync
metadevices_sync="\
d0	${CLONE}s0
d3	${CLONE}s3
d4	${CLONE}s4
d5	${CLONE}s5
"

# Metadevices not to sync (e.g swap) 
metadevices_nosync="\
d1	${CLONE}s1
"

# Temp mount point
MNT=/tmp/_clone_mnt

# Logfile
LOG=/var/tmp/clone_create.log

# Mail of responsible user
MAIL=root


#
# Do not edit below this line
#



md_tmp=` metastat -p|sort +1n  | tail -1| sed 's/^d//g'|awk '{print "d"$1+1}' `
#
msg1="can't create metadevice"
msg2="can't attach metadevice"
msg3="can't detach metadevice"
msg4="can't clear metadevice"
msg5="fsck failed"
msg6="can't mount filesystem"
msg7="can't unmount filesystem"
msg8="metadevice wrong state"


raise_err()
{
 echo "Error: $1" >>$LOG
 echo "Unable to continue" >>$LOG
 cat $LOG|mailx -s "`hostname`: cloning error" $MAIL
 exit 1
}

resync_cycle()
{
echo "Resync in progress" >>$LOG
while true; do
 metastat $1 |grep "Resync in progress" >/dev/null || break
 sleep 180
done
metastat $1 |grep "State:"|grep -v Okay >/dev/null && raise_err "$msg8"
}

prtvtoc -h /dev/rdsk/${ROOT}s2| fmthard -s - /dev/rdsk/${CLONE}s2
cd /usr/platform/`uname -m`/lib/fs/ufs
installboot bootblk /dev/rdsk/$rootvol


printf "$metadevices_sync" | while read md slice
do
	echo "Starting to create clone of metadevice $md to $slice at `date '+%d/%m/%y %H:%M:%S'`" >>$LOG
	metainit $md_tmp 1 1 $slice >>$LOG 2>&1 || raise_err "$msg1"
	metattach $md $md_tmp >>$LOG 2>&1 || raise_err "$msg2"	
	resync_cycle $md
	metadetach $md $md_tmp
	metaclear $md_tmp
	echo "Checking clone filesystem $slice" >>$LOG
	fsck -y /dev/rdsk/$slice >>$LOG 2>&1 || raise_err "$msg5"
done

echo "Tweak system config files" >>$LOG
[ -d $MNT ] || mkdir $MNT
mount /dev/dsk/$rootvol $MNT >>$LOG 2>&1 || raise_err "$msg6"

fstab_tmp=/tmp/vfstab.$$
cat /etc/vfstab > ${fstab_tmp}

printf "$metadevices_sync $metadevices_nosync" | while read md slice
do
	cat ${fstab_tmp} | sed "s,/dev/md/rdsk/$md[ 	],/dev/rdsk/$slice  ,g"	| sed "s,/dev/md/dsk/$md[ 	],/dev/dsk/$slice  ,g" 	> ${fstab_tmp}_
	cat ${fstab_tmp}_ > ${fstab_tmp}
done

cat ${fstab_tmp} > $MNT/etc/vfstab
rm ${fstab_tmp}
rm ${fstab_tmp}_


cat /etc/system | grep -v rootdev > $MNT/etc/system
umount $MNT >>$LOG 2>&1 || raise_err "$msg7"  

echo "End cloning at `date '+%d/%m/%y %H:%M:%S'`" >>$LOG

