#!/bin/sh

# Generic ramdisk init process for booting a device. Based Marko Saukko's
# initrd for Galaxy Note GT-i9250.
#
# Copyright (C) 2014 Jolla Ltd.
# Copyright (C) 2012 Marko Saukko
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

# IRC: Sage @ #mer & #nemomobile @ Freenode

# Location of the device init script, if not set, few defaults are tried.
INITBIN=/sbin/preinit

# What to mount as rootfs
ROOTDEV="/dev/mmcblk1p1"

# Where to mount the rootfs
ROOTMNTDIR="/rootfs"

fail() {
    echo "Failed"
    echo "$1"
    exec /bin/sh
}

echo "Starting ramdisk.."
mount -a

mkdir -p $ROOTMNTDIR

# Mount the root filesystem
mount $ROOTDEV $ROOTMNTDIR
if [ $? -eq 0 ]; then
	echo "Mounting root succeeded"
else
	fail "Mouting root failed"
fi

echo "Searching for init process..."

if [ -n $INITBIN ] || [ -e $ROOTMNTDIR/$INITBIN ]; then
	echo "Found $INITBIN"
elif [ -e ${ROOTMNTDIR}/usr/sbin/init ]; then
	INITBIN="/usr/sbin/init"
elif [ -e ${ROOTMNTDIR}/sbin/init ]; then
	INITBIN="/sbin/init"
elif [ -e ${ROOTMNTDIR}/init ]; then
	INITBIN="/init"
else
	fail "Unable to find init process from rootfs."
fi

# umount everything before doing switch root as the init process
# is responsible of doing these inside the final boot env.
umount -a

echo "Switching to rootfs at ${ROOTMNTDIR}, with init ${INITBIN}"

# usage: switch_root <newrootdir> <init> <args to init>
exec switch_root ${ROOTMNTDIR} ${INITBIN}

