#!/bin/sh
#
# 	$Source: /cvsroot/bootcd/bootcd/bootcdproberoot,v $
#       $Id: bootcdproberoot,v 1.3 2005/02/08 13:16:35 bs Exp $
#    author: Carsten Dinkelmann <din@foobar-cpa.de>
#     start: 25.01.2005
#     topic: try to detect the root device and set it as new
#
#

# devices: device:major:minor
devices="hda:3:0 hdb:3:64 hdc:22:0 hdd:22:64 hde:33:0 hdf:33:64 hdg:34:0 hdf:34:64 scd0:11:0 scd1:11:2 scd2:11:3 scd3:11:4 scd4:11:5 scd5:11:6 scd6:11:7 scd7:11:8"

# search for this file on the cd
bootcdfile="/etc.ro/bootcd/bootcd2disk.conf"

################### nothing to configure behind this line #####################

devs=""
rootdev=""

oldroot=$(cat /proc/sys/kernel/real-root-dev)

# search all hd* which inludes ide-cdrom in driver
echo >&2 "try to find ide-cdrom: "
for i in $(cd /proc/ide; ls hd*); do
   is=$(cat /proc/ide/$i/driver)
   if [ "$(echo "$is" |grep "ide-cdrom")" ]; then
     echo >&2 "- $i ... found cdrom ($is) "
     devs=$(echo "$devs$i ")
   else
     echo >&2 "- $i ... no cdrom    ($is) "
   fi
done

# ok, simple grep for scsi-cdroms ;-)
echo >&2 "try to find scsi-cdrom: "
nr=$(cat /proc/scsi/scsi |grep "Type:[[:space:]]*CD-ROM"  |wc -l)
i=0
while [ $i -lt $nr ]; do
  echo >&2 "- scd$i ... found cdrom "
  devs=$(echo "${devs}scd$i ")
  i=$(expr $i + 1)
done

echo "search for bootcd on this devices: $devs"

# try to mount the selected devices to /mnt
# (mknod device, try the mount, look for file $file)
for i in $devs; do
   # search right device
   mm=""
   for d in $devices; do
      if [ "$(echo $d|grep $i)" ]; then
        mm=$d;
        break;
      fi
   done
   if [ -z "$mm" ]; then
     echo "Can't find major and minor for device \"$i\" ... please add to /usr/share/bootcd/bootcdproberoot!"
     break; 
   fi 
   # create device
   ret=$(mknod /dev2/$i b $(echo $mm| cut -d":" -f2) $(echo $mm| cut -d":" -f3))

   ret=$(mount -n /dev2/$i /mnt >/dev/null 2>&1; echo $?)
   if [ $ret != 0 ]; then
     echo "- not found on $i (not mountable)"
   elif [ -e "/mnt/$bootcdfile" ]; then 
       echo "- found bootcd on $i"
       umount /mnt
       rootdev=$i
       break;
   else
     echo "- not found on $i"
     umount /mnt
   fi
done

if [ "$rootdev" ]; then
  eval "$(stat -c 'major=$((0x%t)); minor=$((0x%T))' "/dev2/$rootdev")"
  a1=$(($major << 8))
  # dbg: echo "found bootcd on $rootdev ($major/$minor) = "$(expr $a1 + $minor)
  echo "found bootcd on $rootdev and set as new root!"
  echo $(expr $a1 + $minor) >/proc/sys/kernel/real-root-dev
else
  echo "Can't find bootcd so don't change it"
fi

# For DEBUG enable /bin/sh
# /bin/sh
