#!/bin/busybox sh

rescue_shell() {
  echo "$@"
  echo "Dropping to rescue shell, system will reboot when done"
  busybox --install -s
  /bin/sh
  umount -n -a
  sync
  sleep 2
  sync
  reboot -f
  exit
}

echo -e "\033[0;36m*** Felix' btrfs initramfs ***\033[0m"

mount -n -t proc none /proc    || rescue_shell "Cannot mount /proc"
mount -n -t sysfs none /sys    || rescue_shell "Cannot mount /sys"
mount -n -t devtmpfs none /dev || rescue_shell "Cannot mount /dev"

# btrfs device scan
/bin/btrfs device scan || rescue_shell "Cannot scan for btrfs devices"

cmdline=`cat /proc/cmdline`

# real root volume
if [ -z "$root" ]; then
  root="${cmdline##* root=}"
  [ "$root" = "$cmdline" ] && rescue_shell "No root given"
  root="${root%% *}"
fi
# flags for mounting the root volume
if [ -z "$rootflags" ]; then
  rootflags="${cmdline##* rootflags=}"
  [ "$rootflags" = "$cmdline" ] && rootflags=""
  rootflags="${rootflags%% *}"
  [ -z "$rootflags" ] && rootflags="ro,noatime,nodiratime"
fi

# if "dorescue" was passed to the kernel, drop to a rescue shell
grep -q dorescue /proc/cmdline && rescue_shell "Requested by commandline option"

# mount the root volume
mount -n -t btrfs -o "$rootflags" "$root" /mnt || rescue_shell "Cannot mount /mnt"

umount -n /dev  || rescue_shell "Cannot unmount /dev"
umount -n /sys  || rescue_shell "Cannot unmount /sys"
umount -n /proc || rescue_shell "Cannot unmount /proc"

echo -e "\033[0;36m*** READY ***\033[0m"

# pivot root volume and start real init
exec switch_root /mnt /sbin/init
rescue_shell "Cannot switch root"
