#!/bin/sh

# System initialization sequence:
#
# /init (this file)
#  |
#  +--(1) /etc/01_prepare.sh
#  |
#  +--(2) /etc/02_overlay.sh
#          |
#          +-- /etc/03_init.sh
#               |
#               +-- /sbin/init
#                    |
#                    +--(1) /etc/04_bootscript.sh
#                    |       |
#                    |       +-- udhcpc
#                    |           |
#                    |           +-- /etc/05_rc.udhcp
#                    |
#                    +--(2) /bin/sh (Alt + F1, main console)
#                    |
#                    +--(2) /bin/sh (Alt + F2)
#                    |
#                    +--(2) /bin/sh (Alt + F3)
#                    |
#                    +--(2) /bin/sh (Alt + F4)

echo "Welcome to \"Minimal Linux Live\" (/init)"

# Let's mount all core file systems.
/etc/01_prepare.sh

# Print message on screen.
cat << CEOF

  Press empty key (ESC, TAB, SPACE, ENTER) or wait 5 seconds to continue with
  the overlay initialization process. Press any other key for PID 1 rescue shell
  inside the initramfs area.

CEOF

# Wait 5 second or until any keybord key is pressed.
read -t 5 -n1 -s key

if [ ! "$key" = "" ] ; then
  # Print message on screen.
  cat << CEOF
  This is PID 1 rescue shell inside the initramfs area. Execute the following in
  order to continue with the overlay initialization process:

  exec /etc/02_overlay.sh
  
  Execute the following in order to skip the overlay initialization and continue
  directly with the system initialization:

  exec /sbin/init

CEOF

  # Set flag which indicates that we have obtained controlling terminal.
  export PID1_SHELL=true
  
  # Interactive shell with controlling tty as PID 1.
  exec setsid cttyhack sh
fi

# Create new mountpoint in RAM, make it our new root location and overlay it
# with our storage area (if overlay area exists at all). This operation invokes
# the script '/etc/03_init.sh' as the new init process.
exec /etc/02_overlay.sh

echo "(/init) - you can never see this unless there is a serious bug..."

# Wait until any key has been pressed.
read -n1 -s