#!/bin/busybox sh

export PATH=/bin:/sbin

rescue_shell() {
  echo -en "\033[0;36m"
  echo "$@"
  echo -e "Dropping to rescue shell, system will reboot when done\033[0m"
  busybox --install -s
  /bin/sh
  umount -n -a
  sync
  sleep 2
  sync
  reboot -f
  exit
}

echo -e "\033[0;36m*** Felix' LVM 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"

# lvm device scan
export DM_DISABLE_UDEV=1
vgscan    --ignorelockingfailure --mknodes    -P      || rescue_shell "Cannot scan volume groups"
vgchange  --ignorelockingfailure --noudevsync -P -a y || rescue_shell "Cannot activate volume groups"
vgmknodes --ignorelockingfailure                      || rescue_shell "Cannot create device nodes"

cmdline=`cat /proc/cmdline`

# real root volume
if [ -z "$root" ]; then
  root="${cmdline##* root=}"
  [ "$root" = "$cmdline" ] && rescue_shell "No root given"
  root="${root%% *}"
fi
# filesystem type of root volume
if [ -z "$rootfstype" ]; then
  rootfstype="${cmdline##* rootfstype=}"
  [ "$rootfstype" = "$cmdline" ] && rootfstype=""
  rootfstype="${rootfstype%% *}"
  [ -z "$rootfstype" ] && rootfstype="ext4"
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"

# fsck
if grep -q dofsck /proc/cmdline; then
  echo -e "\033[0;36mPress enter to start fsck\033[0m"
  read
  "fsck.$rootfstype" -fv "$root" || rescue_shell "Cannot fsck root fs"
  mount -nr -t "$rootfstype" -o "$rootflags" "$root" /mnt || rescue_shell "Cannot mount /mnt"
  export FSTAB_FILE="/mnt/etc/fstab"
  fsck -ARV -fv || rescue_shell "Cannot fsck filesystems"
  unset FSTAB_FILE
  umount /mnt || rescue_shell "Cannot unmount /mnt"
  echo -e "\033[0;36mPress enter to boot\033[0m"
  read
fi
  
# snapshots for disaster recovery
if grep -q dosnap /proc/cmdline; then
  lvcreate -s "$root" -L 2G -n snaproot
fi

# mount the root volume
mount -n -t "$rootfstype" -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"
