#!/bin/sh 
#set -x
# This script will backup the operating system disk onto
# an extra "mirror" disk for LINUX.
# 
# unmount mirrored copy of each filesystem and run newfs on it.
# Remount the newly created filesystem.
# Run dump over the old filesystem piped into restore on the new filesystem.
# If it is the root partition, edit the /etc/fstab file to reflect the new
# disk device names for the filesystems and install a new boot block.
#
# This script relies on the mirrored partitions being mounted at
# ${MMPT} within the /etc/fstab file
#----------------------------------------------------------------------------------

SLAC="@slac.stanford.edu"
MAILLIST="brobeck$SLAC, jingchen$SLAC, ppascual$SLAC"
HOST=`uname -n`
cmdnm="$HOST-`basename $0`"

# Setup logging
logfile=/tmp/$cmdnm.log
exec > $logfile 2>&1

if [ -d /afs ] 
  then
    LOGDIR="/nfs/slac/g/lcls/sys/log/linuxdd"
  else
    LOGDIR="/u1/lcls/sys/log/linuxdd"
fi
#

trap "trap_exit" 0 1 2 3 15

trap_exit() {
  echo "$ME: Finished at `date`"
} # trap_exit


#
# Initialise variables.  The controller and partitions are common for both
# disks.
#
initialize() 
{
  ME=`basename $0`
  MMPT=/MIRROR 
  LOGFILE=/var/log/mirrorlog
  MAILPROG=mail
  MAILFLAG=fail  # Flag (yes/no/fail) to select e-mail notification conditions:
                 #   yes - always after completion (success or fail)
                 #   no  - never
                 #  fail - only on failures
 
#  MAILTO=root    # E-mail recipient for mail notices
  MAILTO=controls-system-admins@slac.stanford.edu  # E-mail recipient 
  MSG="$ME: Successful Completion on `uname -n`"


} # initialise

determine_mkfs_command()
{
grep " / " /etc/fstab | grep ext3 > /dev/null 2>&1

if [ $? -eq 0 ]
then
mkfs_command="/sbin/mkfs.ext3"
fi

grep " / " /etc/fstab | grep ext4
if [ $? -eq 0 ]
then
mkfs_command="/sbin/mkfs.ext4"
fi
}

#
# Called whenver an abnormal termination is needed.
#
send_notice()
{
if [ "$MAILFLAG" != 'no' ] ; then
    $MAILPROG -s "?(${ME}) FAILED on `uname -n`" $MAILTO < $LOGFILE
fi 
} #send_notice


#
# This routine is the guts, it does the basic steps mentioned above.
# The parameter is the partition number variable definied in initialise.
#

label2dev()
{

declare -a MYRA
MYRA=($(/bin/grep LABEL /etc/fstab | /bin/cut -d " " -f 1))

#iecho number of elements ${#MYRA[*]}
#echo number of elements ${#MYRA[@]}
/bin/cp /etc/fstab /etc/fstab.bkup
/bin/cp /etc/fstab /etc/fstab.intermed
for LABELID in ${MYRA[@]}
do
        DEVNAME=($(/sbin/blkid -t $LABELID | /bin/cut -d " " -f 1 | /bin/cut -d ":" -f1))
        if [ "$DEVNAME" != "" ]
        then

                echo Replacing $LABELID with $DEVNAME
                /bin/cat /etc/fstab.intermed |/bin/sed "s#$LABELID #$DEVNAME #g" > /etc/fstab.intermed2
                /bin/cp /etc/fstab.intermed2 /etc/fstab.intermed
                rm -rf /etc/fstab.intermed2
        else
                echo blank
        fi
done
        /bin/mv /etc/fstab.intermed /etc/fstab
}

initrd_func()
{
  echo "Making special initrd"
  mkdir /var/tmp/MIRRORSCRIPT_initrd
  cd /var/tmp/MIRRORSCRIPT_initrd
  /bin/gzip -dc < /boot/initrd-`uname -r`.img | cpio -i
  /bin/sed -r --in-place "s/vg00/vg01/g" init
  find . | cpio -o -c | gzip -9 > ${MMPT}_boot/initrd-`uname -r`MIRROR.img
  cd /var/tmp
  rm -rf MIRRORSCRIPT_initrd

}


backup_partition() 
{
echo "Backing Up..."
cat /etc/fstab | grep MIRROR |  awk '{print $1, $2}' | while read mountpoint
do
tempvar1=`echo $mountpoint| awk '{print $2}' | sed 's/\/MIRROR_/\//g'| sed 's/_/\//g' | sed 's/\/root/\//g'`
tempvar2=`echo $mountpoint $tempvar1`
set $tempvar2

cd $2
/sbin/dump 0uf - $3 |  /sbin/restore rf - $2 ;cd -


    if [ $? -ne 0 ] ; then
      MSG="$ME: dump or restore of ${$tempvar1} failed. Aborting. Mirror not valid.  Re-mounting mirror partitions"
      echo $MSG
      send_notice
      exit 1
    fi
    echo "$tempvar1 copied successfully.\n"

  done

} # backup_partition



update_fstab_on_mirror()
{
  echo "Updating fstab on mirror"
  # Backup fstab
  /bin/mv ${MMPT}_root/etc/fstab ${MMPT}_root/etc/fstab.old
  if [ $? -ne 0 ] ; then
    MSG="$ME: Unable to mv ${MMPT}_root/etc/fstab.  Aborting.  Mirror not bootable."
    echo $MSG
    send_notice
    exit 1
  fi

  #
  # Two /bin/seds.  The first removes backup entries, the second loop subs all device refs for the mirror partitions.
  #
 /bin/grep -v ${MMPT} ${MMPT}_root/etc/fstab.old > ${MMPT}_root/etc/fstab
  if [ $? -ne 0 ] ; then
    MSG="$ME: Unable to create ${MMPT}_root/etc/fstab.new.  Aborting.  Mirror not bootable."
    echo $MSG
    send_notice
    exit 1
  fi

} # update fstab


# Mount mirror partitions
mount_mirror()
{
	for MOUNTPATH in $(/bin/grep ${MMPT} /etc/fstab | /bin/awk '{print $2}')
	do
		/bin/mount $MOUNTPATH > /dev/null
        if [ $? -ne 0 ] ; then
        MSG="$ME: Unable to mount $MOUNTPATH  Aborting.  Mirror not bootable."
        echo $MSG
        send_notice
        exit 1
        fi
      
	done

} # mount_mirror


fsck_mirror()
{
echo "sleep for 10 seconds"
sleep 10

        for FILESYSTEM in $(/bin/grep ${MMPT} /etc/fstab | /bin/grep -v "^#"| /bin/awk '{rows[i++]=$0}END{while(i>=0)print rows[i--]}' | /bin/grep -v "^$" | /bin/awk '{print $1}')
do
	/sbin/fsck.ext3 -y $FILESYSTEM
done
}

mkfs_mirror()
{
echo "sleep for 5 seconds"
sleep 5 

        for FILESYSTEM in $(/bin/grep ${MMPT} /etc/fstab | /bin/grep -v "^#"| /bin/awk '{rows[i++]=$0}END{while(i>=0)print rows[i--]}' | /bin/grep -v "^$" | /bin/awk '{print $1}')
do
        $mkfs_command  $FILESYSTEM
done
}

#
# Unmount mirror partitions
unmount_mirror()
{
sleep 10
        for MOUNTPATH in $(/bin/grep ${MMPT} /etc/fstab | /bin/grep -v "^#"| /bin/awk '{rows[i++]=$0}END{while(i>=0)print rows[i--]}' | /bin/grep -v "^$" | /bin/awk '{print $2}')
do
                COUNTER=0
                LOOPVER=1
                while [ $LOOPVER -eq 1 ] ; do
                        /bin/umount $MOUNTPATH
                        if [ $? -ne 0 ]; then
                                ((COUNTER=COUNTER + 1))
                                if [ $COUNTER -lt 10 ] ; then
                                        MSG="$ME: ***Could not unmount $MOUNTPATH*** Try #$COUNTER. Retrying..."
                                        echo $MSG
                                        sleep 10
                                else
                                        MSG="$ME: ***Could not unmount $MOUNTPATH*** Re-mounting MIRROR Partitions"
                                        echo $MSG
                                        send_notice
                                        mount_mirror
                                        exit 1

                                fi
                        else
                                break
                        fi
                done

        done

} # unmount_mirror


create_mount_points_for_mirror()
{
#Find out what's our root disk
ROOT_DISK=` df / | grep dev | sed 's/ .*//' |  sed 's/[0-9]*//g' | sed 's/\/dev\///g'`

mkdir /MIRROR_root
for mountpoint in `grep $ROOT_DISK /etc/fstab | grep -v swap | grep -v "^#" | awk '{print $2}' | grep -v "/$" |  sed 's/\//_/g' | awk '{print "MIRROR"$1}'`
do
mkdir /$mountpoint
done

}


convert_labels_in_fstab()
{
#'Only update fstab on active drive if LABEL still exists and is not commented or nor SW-cciss
  /bin/grep -v '^#' /etc/fstab | /bin/grep -v 'SW-' | /bin/grep LABEL  > /dev/null
  if [ $? -eq 0 ] ; then
    label2dev
  fi
}


check_before_starting()
{

/sbin/fdisk -l | grep -i disk | grep sdb
if [ $? -eq 0 ]
then
echo "Disk sdb exists and will partition that"

else
echo  "Disk sdb DOES NOT exist. Aborting... Please check"
exit 1
fi

/bin/mount | grep sdb
if [ $? -eq 0 ]
then
echo "some of the sdb partitions are mounted. Won't proceed. Please check"
exit 1
fi

grep sdb /etc/fstab
if [ $? -eq 0 ]
then
echo "I see entries related to sdb in /etc/fstab. Won't proceed. Please check"
exit 1
fi

}



add_entries_in_fstab_for_mirror()
{
#----------------------------------------------------------------------
# This script will make modifications to the /etc/fstab so our disk 
# mirroring script: linux-mirror can perform the disk mirroring.  
# This script will also make the mount points.
#-----------------------------------------------------------------------
#
WDIR=/etc
FILE=$WDIR/fstab
WCOPY=$WDIR/fstab.work
FCOPY=$WDIR/fstab.final
DATE=`date +%m-%d-%Y-%H:%M`
#----------------------------------------------------
# Make a copy of the original fstab
# Make a copy to work with
# Make a final copy that will have the modifications
#----------------------------------------------------
cp -f $FILE $FILE-$DATE
cp -f $FILE $WCOPY
cp -f $FILE $FCOPY
#---------------------------------
# Make the MIRROR mounts in fstab
#---------------------------------
cat /etc/fstab | grep MIRROR
if [ $? -eq 0 ]
then
echo  "Aborting....There are entries related to MIRROR in /etc/fstab. Remove those and rerun the script"
send_notice
exit 1
fi

cat /etc/fstab | grep sda |  grep -v swap |sed 's/\//_/4' | sed 's/\//_/4' | sed 's/ \/ / \/MIRROR_root /g' | sed 's/\//\/MIRROR_/3' | sed 's/MIRROR_MIRROR/MIRROR/g' | sed 's/sda/sdb/g' > $WCOPY
cat $WCOPY >> $FILE

}


fdisk_on_mirror_drive()
{
/sbin/fdisk -l | grep -i disk | grep sdb
if [ $? -eq 0 ]
then
echo "Disk sdb exists and will partition that"
/sbin/sfdisk -d /dev/sda | /sbin/sfdisk --force /dev/sdb
sleep 5
partprobe /dev/sdb
else
echo  "Disk sdb DOES NOT exist. Aborting... Please check"
exit 1
fi
}

create_swap_on_mirror()
{
echo "BEFORE issuing the mkswap command"
swap_part=`cat /etc/fstab | grep swap | awk '{print $1}' | sed 's/sda/sdb/'`
echo "swap_part is $swap_part"
#/sbin/mkswap `cat /etc/fstab | grep swap | awk '{print $1}' | sed 's/sda/sdb/'`
/sbin/mkswap $swap_part 
echo "AFTER mkswap command"
partprobe /dev/sdb
echo "sleep 10 seconds AFTER partprobe command"
sleep 10
}

restore_original_fstab()
{
/bin/cp /etc/fstab  /etc/fstab_for_disk_mirroring
/bin/cat  /etc/fstab_for_disk_mirroring | /bin/grep -vi MIRROR   | /bin/grep -v sdb > /etc/fstab
}

remove_mirror_directories_on_primary()
{
rmdir /MIRROR_*
}


install_grub()
{
grep  "/boot"  /etc/fstab
if [ $? -eq 0 ]
  then
    echo "we have separate boot partition"
    /sbin/grub --batch --device-map=${MMPT}_boot/grub/device.map  --config-file=${MMPT}_boot/grub/grub.conf <<EOF
device (hd0) /dev/sdb
root (hd0,0)
setup (hd0)
quit
EOF

else
    echo "we do not have separate boot partition"
    IF5=`cat /etc/redhat-release | grep "release 5" >/dev/null;echo $?`
    IF6=`cat /etc/redhat-release | grep "release 6" >/dev/null;echo $?`
    if [ "$IF6" == 0 ] || [ "$IF5" == 0 ]
      then
	echo "--Grub for RHEL5 or RHEL6"
	/sbin/grub-install --recheck --root-directory=/MIRROR_root /dev/sdb
      else
	echo "--Grub for RHEL7"
	/sbin/grub2-install --recheck  /dev/sdb
    fi
fi
}

remove_MIRROR_dirs_from_mirror_disk()
{
rmdir /MIRROR_*/MIRROR_*
}

#################################################################
##
## M A I N
##
#################################################################

check_before_starting
echo "FINISHED ******************check_before_starting"
initialize
echo "FINISHED ****************** initialize"
convert_labels_in_fstab
echo "FINISHED ****************** convert_labels_in_fstab"
add_entries_in_fstab_for_mirror
echo "FINISHED ****************** add_entries_in_fstab_for_mirror"
fdisk_on_mirror_drive
echo "FINISHED ****************** fdisk_on_mirror_drive"
sleep 5 
determine_mkfs_command
echo "FINISHED ******************  determine_mkfs_command"
mkfs_mirror
echo "FINISHED ******************mkfs_mirror"
create_swap_on_mirror
echo "FINISHED ****************** create_swap_on_mirror"
create_mount_points_for_mirror
echo "FINISHED ****************** create_mount_points_for_mirror"
mount_mirror
echo "FINISHED ****************** mount_mirror"
backup_partition
echo "FINISHED ******************  backup_partition"
install_grub
echo "Finished grub-install"
#/sbin/grub-install --recheck --root-directory=/MIRROR_root /dev/sdb
update_fstab_on_mirror
echo "FINISHED ******************  update_fstab_on_mirror"
remove_MIRROR_dirs_from_mirror_disk
echo "FINISHED ****************** remove_MIRROR_dirs_from_mirror_disk"
unmount_mirror
echo "FINISHED ****************** unmount_mirror"
fsck_mirror
echo "FINISHED ****************** fsck_mirror"
remove_mirror_directories_on_primary
echo "FINISHED ****************** remove_mirror_directories_on_primary"
restore_original_fstab
echo "FINISHED ****************** restore_original_fstab"
echo "${ME}: Successful completion!"
#
#Copy over Logfile
su laci -c "cp /tmp/${cmdnm}.log $LOGDIR/${cmdnm}.log"
cat -v $LOGDIR/${cmdnm}.log | mailx -s "$cmdnm SUCCESS" $MAILLIST
exit 0
