#!/bin/sh
#
# This is the first script run in the system (started by the kernel).
#
# (C) Copyright 2003-2008 Axis Communications AB, LUND, SWEDEN
# This file is released under the GPL v2.


FLASHMP=/mnt/flash

echo -n "$0: Mounting /dev... "
if /bin/mount -t tmpfs udev /dev; then
	echo "done"
else
	echo "failed!"
fi
cd /
echo -n "$0: Populating /dev... "
if /bin/tar -xf .dev.tar; then
	echo "done"
else
	echo "failed!"
fi

if [ -x /sbin/rc.factorydefault ]; then
	/sbin/rc.factorydefault ||
		echo "$0: /sbin/rc.factorydefault failed!" >&2
fi

MOUNT=
[ -f /usr/share/axis-release/variables ] && . /usr/share/axis-release/variables
[ "$FS_TYPE_part_rwfs" ] || FS_TYPE_part_rwfs=jffs2
[ "$MOUNT" ] || MOUNT="/bin/mount -t $FS_TYPE_part_rwfs /dev/part/rwfsblock $FLASHMP $MOPTS_part_rwfs"

echo -n "$0: Mounting $FLASHMP... "
if $MOUNT; then
	echo "done"
else
	echo "failed!"

	if [ -x /sbin/rc.factorydefault ]; then
		echo "$0: Forcing factory default!"
		/sbin/rc.factorydefault --force ||
			echo "$0: /sbin/rc.factorydefault failed!" >&2

		echo -n "$0: Mounting $FLASHMP... "
		if $MOUNT; then
			echo "done"
		else
			echo "failed! Starting a shell."
			exec /bin/sh
			echo "$0: Failed to start a shell!" >&2
			exit 1
		fi
	else
		echo "$0: Cannot execute /sbin/rc.factorydefault!" \
		     "Starting a shell." >&2
		exec /bin/sh
		echo "$0: Failed to start a shell!" >&2
		exit 1
	fi
fi

if [ -x /sbin/rc.fsupgrade ]; then
	/sbin/rc.fsupgrade || echo "$0: /sbin/rc.fsupgrade failed!" >&2
fi

echo "$0: Starting init."

# Unset variable exported by sh.
unset PWD

# Try the same paths as the kernel would.
PATH=/sbin:/etc:/bin
exec init "$@"

echo "$0: No init found! Starting a shell instead." >&2
exec /bin/sh

echo "$0: Failed to start a shell!" >&2
exit 1
