#!/bin/sh
# -*- mode: shell-script; indent-tabs-mode: nil; sh-basic-offset: 4; -*-
# ex: ts=8 sw=4 sts=4 et filetype=sh

if [[ "$root" = "mgainstaller" ]]; then
    mkdir -p /run/drakx

    # Turn off kernel messages while we run stage1 (it messes up curses control)
    stage1printk=
    if [[ -f /proc/sys/kernel/printk ]]; then
      stage1printk=$(cat /proc/sys/kernel/printk)
      echo '0 0 0 0' >/proc/sys/kernel/printk
    fi

    # Run stage1 This ensures that stage2 is available and mounted on /tmp/stage2
    # Note: We could run this later but it makes sense to do it at the "correct"
    # time in the dracut init stage.
    stage1rv="53" # 0x35
    while [[ "$stage1rv" = "53" ]]; do
      stage1
      stage1rv=$?
      if [[ "$stage1rv" = "66" ]]; then
        # exit code 66 is "proceed" aka, run /sbin/init after doing some
        # symlinking/bind mounts
        >/run/drakx/run-init
      fi
    done

    # Restore kernel messages
    if [[ -n "$stage1printk" ]]; then
      echo "$stage1printk" >/proc/sys/kernel/printk
    fi

    # Create a fake sysroot to please dracut and allow it to continue
    # Our stage2 reuses the root environment provided by the initrd.
    # We do not actually switch to a new root. Hence we hack over the switch_root
    # command to allow dracut to continue as normal (shutting down udev etc.)
    # before we take over again later. As there are no hook points at later
    # stages, this is the cleanest way without modifying dracut itself

    # /sysroot has to be a mountpoint
    mount -t tmpfs -o mode=755,nodev,nosuid none /sysroot

    # Fool usable_root()
    mkdir -p /sysroot/dev
    mkdir -p /sysroot/proc
    mkdir -p /sysroot/sys

    # Create a fake init (it will never be run)
    mkdir -p /sysroot/sbin
    >/sysroot/sbin/init
    chmod  a+x /sysroot/sbin/init

    # Inject our fake switch_root to run stage2
    mv /usr/sbin/switch_root /usr/sbin/switch_root.real
    ln -sf stage2-fake-switch_root /usr/sbin/switch_root
fi
