#!/bin/sh

I_AM=`whoami`
if [ "$I_AM" != "root" ]; then
  echo -e "This action requires root privileges.\n"
  exit 1
fi

TMP=/var/log/setup/tmp
if [ ! -d $TMP ]; then
 mkdir -p $TMP
 chmod 700 $TMP
fi

if [ ! -d lost+found -a ! -d vmlinuz -a ! -d proc ]; then # cheap, but it works :^)
 cd /
fi

#
############################################################################
#			 Question and answer.
############################################################################
#
cat << EOF > $TMP/tempmsg
Now we will attempt to configure your USB controller.
You can reconfigure your system at any time by typing:

  usbconfig

EOF
dialog --title "USB CONFIGURATION" --msgbox "`cat $TMP/tempmsg`" 9 70


# autodetection
for card in uhci usb-ohci usb-uhci ; do
  chroot . /sbin/modprobe $card 2> /dev/null
  if [ $? = 0 ]; then
    dialog --title "CONTROLLER DETECTED" --msgbox "USB controller using the $card.o module has been detected." 5 72
    echo "$card" > /cardfound
    break;
  fi
done

# autodetection ehci
rm -f /ehcifound
card=ehci-hcd
chroot . /sbin/modprobe $card 2> /dev/null
if [ $? = 0 ]; then
  dialog --title "CONTROLLER DETECTED" --msgbox "USB controller using the $card.o module has been detected." 5 72
  echo "$card" > /ehcifound
  break;
fi


if [ -r /cardfound ]; then
  if [ ! "`cat /cardfound`" = "" ]; then
    cat << EOF > etc/rc.modules.d/usb
# Load module for USB controller/devices.
# This script is automatically generated by the usbconfig

/sbin/modprobe `cat /cardfound`

EOF
    if [ -r /ehcifound ]; then
      echo "/sbin/modprobe `cat /ehcifound`" >> etc/rc.modules.d/usb
      echo "" >> etc/rc.modules.d/usb
    fi
    chmod 755 etc/rc.modules.d/usb
  fi

  dialog --separate-output --checklist "Which USB devices do you want to use?" 10 75 15 \
  hid "Human Interface Device - Keyboard, mouse, ..." on \
  usb-storage "USB Storage - USB flash, USB harddrive/rack, ... " on \
  2> /tmp/return

  if [ $? = 1 -o $? = 255 ]; then
    rm -f $TMP/tempmsg /cardfound /tmp/return
    exit 1;
  fi

  cat /tmp/return | while read line ; do
    echo "/sbin/modprobe $line" >> etc/rc.modules.d/usb
    chroot . /sbin/modprobe $line 2> /dev/null
  done
  rm -f /tmp/return

  dialog --title "USB SETUP COMPLETE" --msgbox "USB support has been configured." 5 68
else
  cat << EOF > $TMP/tempmsg
Sorry. No supported USB controller found !
If your controler is based on the 'sl811' chipset,
then try to configure the module manually.
EOF
  dialog --title "NO CONTROLLER DETECTED" --msgbox "`cat $TMP/tempmsg`" 8 62
fi

rm -f $TMP/tempmsg /cardfound

