#!/bin/sh

UPDATE_DIR=/storage/.update

IMAGE_SYSTEM="SYSTEM"
IMAGE_KERNEL="KERNEL"
REBOOT=0

# mount all needed special filesystems
  /bin/busybox mount -t devtmpfs none /dev
  /bin/busybox mount -t proc none /proc

# parse command line arguments
  for arg in $(cat /proc/cmdline); do
    case $arg in
      debugging)
        DEBUG=yes
        ;;
      splash)
        SPLASH=yes
        ;;
      bootchart)
        BOOTCHART=yes
        ;;
      fastboot)
        FASTBOOT=yes
        ;;
    esac
  done

  if test "$FASTBOOT" = yes; then
    IONICE="/bin/busybox ionice -c 1 -n 0"
  fi

  progress() {
    if test "$DEBUG" = yes; then
      echo "### $1 ###"
    fi
  }

  error() {
    echo "Error Code: $1 that means: $2"
  }

  debug_shell() {
    echo "### Starting debugging shell... type  exit  to quit ###"
    /bin/busybox sh </dev/tty1 >/dev/tty1 2>&1
  }

  mount_part() {
    progress "trying to mount $1 ..."
    for i in 1 2 3 4 5 6 7 8 9 10; do
      ERR_ENV=1
      $IONICE /bin/busybox mount -o $3 $1 $2 > /dev/null 2>&1
      [ $? -eq 0 ] && ERR_ENV=0 && break
      /bin/busybox usleep 1000000
    done
    [ $ERR_ENV -ne 0 ] && error "INIT_4" "Could not mount $1" && debug_shell
  }

  update() {
    if [ -f "$UPDATE_DIR/$2" ]; then
      echo "updating $1..."
        $IONICE /bin/busybox mount -o remount,rw /flash
        $IONICE /bin/busybox mv $UPDATE_DIR/$2 $3
        $IONICE /bin/busybox mount -o remount,ro /flash
        $IONICE /bin/busybox sync
        [ $2 = $IMAGE_KERNEL ] && REBOOT=1
    fi
  }

  mount_part "$boot" "/flash" "ro,noatime"
  mount_part "$disk" "/storage" "rw,noatime"

  update "Kernel" "$IMAGE_KERNEL" "/flash/$IMAGE_KERNEL"
  update "System" "$IMAGE_SYSTEM" "/flash/$IMAGE_SYSTEM"

  if test "$REBOOT" -eq 1; then
    echo "System reboots now..." && \
    /bin/busybox reboot
  fi

  if [ -f "/flash/$IMAGE_SYSTEM" ]; then
    mount_part "/flash/$IMAGE_SYSTEM" "/sysroot" "loop"
    [ $ERR_ENV -ne 0 ] && debug_shell
  else
    error "INIT_2" "Could not find system."
    debug_shell
  fi

# move /flash and /storage to /sysroot
  /bin/busybox mount --move /flash /sysroot/flash
  /bin/busybox mount --move /storage /sysroot/storage

# unmount all other filesystems
  /bin/busybox umount /dev
  /bin/busybox umount /proc

# switch to new sysroot and start real init
  exec /bin/busybox switch_root /sysroot /sbin/init

  error "INIT_3" "Error in initramfs. Could not switch to new root"
  debug_shell
