#!/bin/sh
# $Id: firstboot,v 1.1 2004/08/12 05:47:00 mbm Exp $


[ -f "/tmp/.firstboot" ] && {
	echo "firstboot is already running"
	return
}
touch /tmp/.firstboot

jdev=$(mount | awk '/jffs2/ {print $3}')

if [ -z "$jdev" ]; then
	echo -n "Creating jffs2 partition... "
	mtd erase OpenWrt >&- 
	mount -t jffs2 /dev/mtdblock/4 /jffs
	echo "done"
	cd /jffs
else
	echo "firstboot has already been run"
	echo "jffs2 partition is mounted, only resetting files"
	cd $jdev
fi

outdev=/dev/null
test -e /dev/tts/0 && outdev=/dev/tts/0
exec 2>$outdev

mount /dev/mtdblock/2 /rom -o ro

echo -n "creating directories... "
{
	cd /rom
	find . -type d
	cd -
} | xargs mkdir
echo "done"

echo -n "setting up symlinks... "
for file in $(cd /rom; find *  -type f; find *  -type l;)
do {
	ln -sf  /rom/$file $file
} done
echo "done"

echo -n "setting up dropbear (takes a while)..."
mkdir -p etc/dropbear
if [ ! -f etc/dropbear/dropbear_dss_host_key ]; then
	dsskey=$(/rom/usr/sbin/nvram get ff_dsskey)
	if [ -n "$dsskey" ] && [ -f /rom/www/cgi-bin/freifunk-upload ]; then
		echo -n $dsskey|/rom/www/cgi-bin/freifunk-upload -a2b>etc/dropbear/dropbear_dss_host_key
		chmod 0600 etc/dropbear/dropbear_dss_host_key
	else
		dropbearkey -t dss -f etc/dropbear/dropbear_dss_host_key
	fi
fi

for link in etc/passwd etc/group etc/shells; do
	test -e $link && rm $link
done
echo "root:*:0:">etc/group
echo "/bin/ash">etc/shells

test -f etc/dropbear/dropbear_dss_host_key && rm etc/init.d/S*telnet

ipks=$(awk '/mtdblocke/ {print $3}' /proc/partitions)
if [ -n "$ipks" ] && [ 2368 -gt $ipks ]; then
	# Save some JFFS2 space on 2 Mb 
	ipks=$(cd /rom;find usr/lib/ipkg -type f|grep -v freifunk)
else
	ipks=usr/lib/ipkg
fi
tar cC /rom $ipks|tar x

export ff_pw="$(/rom/usr/sbin/nvram get ff_pw)"
test -n "$ff_pw" || export ff_pw=admin
if [ -n "${ff_pw##\$1\$*}" ]; then
	# Clear pw. The passwd cmd has /etc/passwd hard wired...
	mkdir /tmp/setpass
	mkdir /tmp/setpass/bin
	mkdir /tmp/setpass/etc
	cp -a /rom/lib /tmp/setpass
	echo "root::0:0:root:/tmp:/bin/ash">/tmp/setpass/etc/passwd
	cp /rom/bin/busybox /tmp/setpass/bin
	ln -s busybox /tmp/setpass/bin/sh
	ln -s busybox /tmp/setpass/bin/echo
	ln -s busybox /tmp/setpass/bin/sleep
	ln -s busybox /tmp/setpass/bin/passwd
	/rom/usr/sbin/chroot /tmp/setpass sh -c 'sh -c "echo \"$ff_pw\";sleep 1;echo \"$ff_pw\""|passwd'
	cp /tmp/setpass/etc/passwd etc/passwd
	rm -r /tmp/setpass
else
	echo "root:$ff_pw:0:0:root:/tmp:/bin/ash">etc/passwd
fi
export ff_pw=
echo "done"

umount /rom
mount none /jffs/proc -t proc
pivot_root /jffs /jffs/rom
mount none /dev  -t devfs
mount none /tmp  -t ramfs
umount /rom/proc
umount /rom/tmp
umount /rom/dev
