#!/bin/bash

export PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin"

mount -t proc proc /proc

modprobe usbcore
modprobe uhci-hcd
modprobe ohci-hcd
modprobe usb-storage
modprobe sd_mod
# enable USB keyboard
modprobe usbkbd

# loop forever
while true
do

  # repeat mount retry 15 times in 1[s] delays
  for st in 1 1 1 1 1  1 1 1 1 1  1 1 1 1 0
  do

    # loop throught all partitions
    for part in `cat /proc/partitions | grep ' sd[a-z][0-9]$' | sed 's#^.* \(sd[a-z][0-9]\)$#\1#'`
    do
      echo "$0: trying mount /dev/$part as root"
      # try mounting this as root
      mount /dev/$part /mnt || continue
      # check if we can boot from this
      test -f /mnt/sbin/init || { umount /mnt ; continue ; }

      echo "$0: booting from /dev/$part"
      # NORMAL BOOT SEQUENCE ON ROOT PARTITION:
      # try booting from /dev/sda1
      # test for user-defined script
      test -f /mnt/t20_preboot && /mnt/t20_preboot
      # continue regular bootprocedure
      umount /proc
      cd /mnt
      mkdir -p initrd
      pivot_root . initrd
      exec chroot . sbin/init < dev/console > dev/console 2>&1
    done # for part

    # wait for a given time befor retry
    sleep $st

  done # for i

  # fallback - in case of no partitions, run shell...
  echo
  echo "$0: running shell - exit it to retry booting"
  lsmod
  cat /proc/modules
  bash

done # while true


# total rescue - we should not ** ever ** get here
echo
echo "$0: couldn't boot from external disk"
echo
exec bash

