#!/bin/sh
set -x

# exec 2>&1 >/tmp/raidconvert.out

exec 2>&1 

# let's assume it's a SCSI system
if grep -q 'sda$' /proc/partitions; then
    disk=sda
else
    # No SCSI Drives is must be IDE
    media=`cat /proc/ide/hda/media`
    if [ $media == "disk" ] ; then
        disk=hda
    fi
fi

set $disk
found=`echo $#`
if [ $found -gt "0" ] ; then
    # Dump out current partitions
    sfdisk -d /dev/$disk > /tmp/oldparts

    # Check if we have any ext2/3 or swap partitions
    if grep -q 'Id=8[23]' /tmp/oldparts; then
        echo -en "\n\nConverting partitions to RAID..." >/dev/tty3
        # Convert ext2/3 and swap partitions to raid autodetect
        sed 's/Id=8[32]/Id=fd/' /tmp/oldparts > /tmp/newparts

        # Find swap partition for future checks
        swap=`grep 'Id=82' /tmp/oldparts | sed "s/$disk\([0-9]\+\) :.*/md\1/"`

        # Loop throught partitions and convert to degraded raid1
        for part in `grep 'Id=8[23]' /tmp/oldparts | sed 's/ :.*//'`; do
            mdpart=`echo $part | sed "s/$disk\([0-9]\+\)/md\1/"`
	
            echo -n "$part..." >/dev/tty3
            mdadm --create $mdpart --run --level=1 --raid-devices=2 $part missing
            if [ "$mdpart" == "$swap" ]; then
                # Recreate swap partition
                mkswap $swap
            else
                # Resize ext2/3 partitions (fix superblock - part 1)
                resize2fs -f $mdpart
            fi
        done

        echo "done" >/dev/tty3

        # Write out new converted partition table
        sfdisk --force /dev/$disk < /tmp/newparts

	echo -e "\nChecking filesystems on converted partitions. This may take a while." >/dev/tty3

        mkdir /mnt/tmp
        for part in `grep 'Id=fd' /tmp/newparts | sed "s/$disk\([0-9]\+\) :.*/md\1/"`; do
            if [ "$part" != "$swap" ]; then
                # Resize ext2/3 partitions (fix superblock - part 2)
                echo -e "\n\nChecking $part..." >/dev/tty3
                e2fsck -f -C0 $part >/dev/tty3

                # Check for /etc/fstab on partitions and convert entries
                mount $part /mnt/tmp
                if [ -r /mnt/tmp/etc/fstab ]; then
                    cat /mnt/tmp/etc/fstab | sed "s/$disk\([0-9]\+\)/md\1/" \
			> /mnt/tmp/etc/fstab.tmp
                    mv /mnt/tmp/etc/fstab.tmp /mnt/tmp/etc/fstab
                fi
                umount /mnt/tmp
            fi
        done
        rmdir /mnt/tmp
        mdadm --stop --scan
    fi
fi
