#!/bin/sh

PATH=/bin:/sbin
export PATH

error() {
  echo "ERROR: $@"
  echo "Dropping to shell"
  echo
  sh
}

init=/sbin/init
root=
rootdelay=
rootfstype=auto
rorw="ro"
rootflags=
rootdev=

mount -n -t devtmpfs devtmpfs /dev
mount -n -t proc proc /proc
mount -n -t sysfs sysfs /sys
mount -n -t tmpfs tmpfs /run

read -r cmdline < /proc/cmdline

for param in $cmdline ; do
  case $param in
    init=*)
      init=${param#init=}
      ;;
    root=*)
      root=${param#root=}
      ;;
    rootdelay=*)
      rootdelay=${param#rootdelay=}
      ;;
    rootfstype=*)
      rootfstype=${param#rootfstype=}
      ;;
    rootflags=*)
      rootflags=${param#rootflags=}
      ;;
    rw)
      rorw="rw"
      ;;
  esac
done

case "$root" in
  /dev/*)
    rootdev=$root
    ;;
  UUID=*)
    eval $root
    rootdev="/dev/disk/by-uuid/$UUID"
    ;;
  LABEL=*)
    eval $root
    rootdev="/dev/disk/by-label/$LABEL"
    ;;
  ZFS=*)
    eval $root
    zfs=true
    rootdev="$ZFS"
    rootfstype=zfs
    ;;
  "")
    error "No root device found"
    ;;
esac

/sbin/udevd --daemon --resolve-names=never
udevadm trigger
udevadm settle

[ -f /etc/mdadm.conf ] && mdadm -As
[ -x /sbin/vgchange ] && /sbin/vgchange --sysinit -a y

if [ -n "$zfs" ]; then
  zpool import rpool -N || error "Failed importing rpool"
fi

[ -n "$rootdelay" ] && sleep "$rootdelay"
[ -n "$rootflags" ] && rootflags="$rootflags,$rorw" || rootflags="$rorw"

mkdir /.root

if ! mount -n -t "$rootfstype" -o "$rootflags" "$rootdev" /.root ; then
  error "Failed to mount root filesystem"
fi

killall -w udevd

exec switch_root /.root "$init" "$@"
