#!/bin/sh

export CONSOLE=/dev/ttyS0
export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/mnt/root/bin:/mnt/root/sbin:/mnt/root

setconsole $CONSOLE
stty -F $CONSOLE ospeed 115200 > /dev/null 2>&1
mount -t proc proc /proc                                   
mount -t sysfs sysfs /sys                                  
hostname ts7500                                   
ts7500ctl --getrtc --resetswitchon --autofeed 2

devmem 0xc8000004 32 0x106
devmem 0xcc000060 32 0x1
let x=`devmem 0xcc000068`
let y=`devmem 0xcc000064`
x=$(((x | y) & 0x1))
if [ "$x" -eq 1 ]; then
  (
	ts7500ctl --redledon
	mount -t tmpfs tmpfs /lib/modules
	tar -x -z -f /modules.tar.gz -C /
	modprobe scsi_mod
	modprobe sd_mod
	modprobe usbcore
	modprobe ehci_hcd
	modprobe usb_storage
	umount /lib/modules
	x=0
	while [ "$x" -lt 150 -a ! -e /sys/block/sda ]; do
		x=$((x+1))
		sleep .1
	done
	mount -o ro /dev/sda1 /mnt/usbdev
	if [ -x /mnt/usbdev/tsinit ]; then 
		/mnt/usbdev/tsinit <$CONSOLE >$CONSOLE 2>&1
	fi
	umount /mnt/usbdev
	ts7500ctl --redledoff
   ) 
fi

(
  xuartctl --server
  ifconfig lo 127.0.0.1 up
  route add -net 127.0.0.0 netmask 255.0.0.0 lo
  sdctl -z 65536 --nbdserver lun0:disc,lun0:part1,lun0:part2,lun0:part3,lun0:part4
  nbd-client 127.0.0.1 7500 /dev/nbd0
  nbd-client 127.0.0.1 7501 /dev/nbd1
  nbd-client 127.0.0.1 7502 /dev/nbd2
  nbd-client 127.0.0.1 7503 /dev/nbd3
  nbd-client 127.0.0.1 7504 /dev/nbd4
  mount -oro /dev/nbd4 /mnt/root
  wait
) </dev/null >/dev/null 2>&1

if [ -e /mnt/root/notrootfs -o -e /mnt/root/fastboot -o ! -e /mnt/root/sbin/init ]; then
  if [ -e /mnt/root/fastboot ]; then
    echo ">> File 'fastboot' found. Booting to initrd instead..." > $CONSOLE
  else
    echo ">> SD Card failed. Booting to initrd..." > $CONSOLE
  fi

  (                                                                               
    mount -t devpts devpts /dev/pts
    mount -t tmpfs none /dev/shm
    ifconfig eth0 192.168.0.50
    telnetd
    mount -t tmpfs tmpfs /tmp
  ) </dev/null >/dev/null 2>&1

  (
    let x=`devmem 0x79000040`
    sec=$((x / 100000))
    tenths=$((x % 100000 / 1000))
    export BOOTTIME=`printf "%d.%02d" $sec $tenths`
    export ENV=/shinit
    exec setsid cttyhack /bin/sh -i
  ) <$CONSOLE >$CONSOLE 2>&1
  wait
fi

if [ -e /mnt/root/sbin/init ]; then
  killall busybox telnetd >/dev/null 2>&1

  cd /mnt/root
  pivot_root . ./initrd
  ./bin/mount -n --move ./initrd/sys ./sys
  ./bin/mount -n --move ./initrd/proc ./proc
  exec ./usr/sbin/chroot . ./sbin/init < .$CONSOLE > .$CONSOLE 2>&1
fi

