#!/bin/sh /etc/rc.common
# Copyright (C) 2006-2011 OpenWrt.org

START=10
STOP=90

PRODMODE=`uci get cmdline.PROD 2> /dev/null`
RDUPMODE=`uci get cmdline.RDUP 2> /dev/null`

uci_apply_defaults() {
	. /lib/functions/system.sh

	cd /etc/uci-defaults || return 0
	files="$(ls)"
	[ -z "$files" ] && return 0
	for file in $files; do
		( . "./$(basename $file)" ) && rm -f "$file"
	done
	uci commit
}

boot() {
	[ -f /proc/mounts ] || /sbin/mount_root
	[ -f /proc/jffs2_bbc ] && echo "S" > /proc/jffs2_bbc
	[ -f /proc/net/vlan/config ] && vconfig set_name_type DEV_PLUS_VID_NO_PAD

	mkdir -p /var/lock
	chmod 1777 /var/lock
	mkdir -p /var/log
	mkdir -p /var/run
	# Add by mbtk
	mkdir -p /var/run/faillock
	ln -s /var/run /run
	ln -s /var/lock /run/lock
	mkdir -p /var/state
	mkdir -p /var/tmp
	mkdir -p /var/camera
	mkdir -p /tmp/.uci
	chmod 0700 /tmp/.uci
	echo 0 > /tmp/dBm
	touch /var/log/wtmp
	touch /var/log/lastlog
	mkdir -p /tmp/resolv.conf.d
	touch /tmp/resolv.conf.d/resolv.conf.auto
	ln -sf /tmp/resolv.conf.d/resolv.conf.auto /tmp/resolv.conf
	grep -q debugfs /proc/filesystems && /bin/mount -o nosuid,nodev,noexec,noatime -t debugfs debugfs /sys/kernel/debug
	grep -q bpf /proc/filesystems && /bin/mount -o nosuid,nodev,noexec,noatime,mode=0700 -t bpf bpffs /sys/fs/bpf
	grep -q pstore /proc/filesystems && /bin/mount -o nosuid,nodev,noexec,noatime -t pstore pstore /sys/fs/pstore
	[ "$FAILSAFE" = "true" ] && touch /tmp/.failsafe

	touch /tmp/.config_pending
	/bin/pppmodem &

	mkdir -p /tmp/.uci
	[ -f /etc/uci-defaults/30_uboot-envtools ] && (. /etc/uci-defaults/30_uboot-envtools)
	/bin/config_generate
	rm -f /tmp/.config_pending
	/sbin/wifi config
	uci_apply_defaults
	sync

        if [ "$PRODMODE" == "0" ] && [ "$RDUPMODE" == "1" ];then
                if [ -d "/media/var/log/Log000" ] && [ -n "$(ls -A /media/var/log/Log000 2>/dev/null)" ]; then
                    for file in /media/var/log/Log000/*.sdl; do
                        [ -e "$file" ] || continue
                        f=$(basename "$file")
                        n=1
                        dst="/media/var/log/${f%.*}.$n.sdl"
                        while [ -e "$dst" ]; do
                            n=$((n + 1))
                            dst="/media/var/log/${f%.*}.$n.sdl"
                        done
                        mv "$file" "$dst"
                    done
                fi
                nice -n -5 /bin/diag &
        fi

	# temporary hack until configd exists
	/sbin/reload_config

	# let mount done early to boot telephony success
	[ -d /tmp/root ] && mount_root done
}
