#!/bin/bash
# ============================================================================
# Script to check for /dev/cciss device and remap to /dev/sd<xx> device
# Necessary for Clonezilla to work properly for imaging
#
# Author: Ron Kelley
# Modified by Steven Shiau <steven _at_ nchc org tw> on 25/Aug/2007
# License: GPL
# 2 actions:
# (1) link the devices in /dev/
# (2) output the convertion table in file $dev_map
# Possible problem:
# When we restore the clonezilla image, how can we make sure the linked device is the one we need ?
# ============================================================================
# The content of output file is like:
# cciss/c0d0: sdb
# cciss/c0d0p1: sdb1
# cciss/c0d0p2: sdb2

# The output file for the mapping
dev_map="$1"

[ -z "$dev_map" ] && echo "No output file! Exit" && exit 1

[ ! -d "/dev/cciss" ] && echo "No /dev/cciss drivers loaded.  Exiting..." && exit

# ------------------------------------------------
# Create an array of all unused /dev/sd<x> devices
# ------------------------------------------------
declare -a scsi_dev
for i in {a..z}
do
   [ ! -b /dev/sd${i} ] && scsi_dev=( "${scsi_dev[@]}" "sd${i}")
done


# ------------------------------------------------
# Start looking for /dev/cciss/c?d? major devices
# and make symbolic links to the next available 
# unused /dev/sd<x> devices
# ------------------------------------------------
index=0
num=""

for a in /dev/cciss/c?d?; do
   # If the device is a block device...
   if [ -b $a ]; then
        # 1st, map the disk
        b=${scsi_dev[$index]}
        echo Linking Device $a to /dev/$b 
        ln -fs $a /dev/$b
        # remove the leading "/dev/", since in /proc/partitions, the device name is not begin with /dev/, it's only like sda
        var="$(echo $a | sed 's|^/dev/||g')"
        echo "$var:$b$num" >> $dev_map
        unset var

        # 2nd, map the partition
        # Find all partitions related to $a (ie /dev/cciss/c0d0p1, /dev/cciss/c0d0p2, etc) 
        for c in ${a}p?; do 
           # If the device is a block device...
           if [ -b $c ]; then
              num="$(echo "$c" | sed s/\^.*p//g)"
              echo Linking Partition $c to $b$num
              ln -fs $c $b$num 
              # remove the leading "/dev/", since in /proc/partitions, the device name is not begin with /dev/, it's only like sda1
              var="$(echo $c | sed 's|^/dev/||g')"
              echo "$var:$b$num" >> $dev_map
              unset var
           fi
        done
     
        # Increment the scsi_dev array index.
        let index+=1
    fi
done
