#!/bin/sh
# Plymouth and a temporary udev instance for the BusyBox root handoff.
BB=/bin/busybox
PLY=/usr/bin/plymouth

client() {
    "$BB" timeout -k 1 3 "$PLY" "$@"
}

stop_udev() {
    if [ -f /run/kshim-udev ]; then
        "$BB" timeout -k 1 5 /usr/bin/udevadm control --exit
        "$BB" rm -f /run/kshim-udev
    fi
}

case "$1" in
    start)
        for option in $("$BB" cat /proc/cmdline); do
            case "$option" in
                plymouth.enable=0|rd.plymouth=0) exit 0 ;;
            esac
        done
        "$BB" mkdir -p /run/plymouth /dev/pts
        "$BB" mount -t devpts -o mode=0620,ptmxmode=0666 devpts /dev/pts || exit 0
        if ! /usr/lib/systemd/systemd-udevd --daemon; then
            echo 'kShim: early udev unavailable; continuing with text boot.' >&2
            exit 0
        fi
        : > /run/kshim-udev
        /usr/bin/udevadm trigger --action=add --subsystem-match=drm \
            --subsystem-match=graphics --subsystem-match=input --subsystem-match=tty
        if "$BB" timeout -k 1 5 /usr/sbin/plymouthd --mode=boot \
                --pid-file=/run/plymouth/pid --attach-to-session; then
            client show-splash
        else
            echo 'kShim: early Plymouth unavailable; continuing with text boot.' >&2
        fi
        ;;
    prepare-newroot)
        stop_udev
        ;;
    newroot)
        # /dev, /proc, /sys and /run are now accessible below the new root.
        # Plymouth chroots there while retaining its DRM, input and log state.
        if client --ping; then
            client update-root-fs --new-root-dir="$2" || client quit
        fi
        ;;
    stop)
        client quit
        stop_udev
        ;;
esac
exit 0
