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

START=10
STOP=98

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

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

dray_boot() {
	local draytek_wl_center_ready=1
	local draytek_mesh_ready=1
	local draytek_F2_ready=0
	
	#Draytek - mount data partition
	#/usr/sbin/draytek_mount_data.sh
	
	# temporarily add in here, character device can be added after kernel module register it.
	rm -f /dev/dray_mesh
	mknod -m 660 /dev/dray_mesh c 237 0

	# DrayTek
	insmod dray_hw > /dev/null 2>&1
	
	#Draytek auto loader upgrade
	/usr/sbin/check_loader

	# draytek_wl_center.ko must be inserted before wireless driver starting
	if [ "$draytek_wl_center_ready" = "1" ]; then
		[ -f /lib/modules/4.4.60/draytek_wl_center.ko ] && insmod draytek_wl_center > /dev/null 2>&1
	fi

	# draytek_mesh_network.ko must be inserted before wireless driver starting
	if [ "$draytek_mesh_ready" = "1" ]; then
		[ -f /lib/modules/4.4.60/draytek_mesh_network.ko ] && insmod draytek_mesh_network > /dev/null 2>&1
	fi

	# F2: detect reboot in "Burn In"
	if [ "$draytek_F2_ready" = "1" ]; then
		test_mode=`nvram_get 2860 test_mode`
	   
		if [ "$test_mode" = "1" ]; then
			# tracking reboot count
			reboot_cnt=`nvram_get 2860 reboot_cnt`
			if [ "$reboot_cnt" = "" ]; then
				reboot_cnt=0
			else
				reboot_cnt=$((reboot_cnt+1))
			fi
			echo "reboot_cnt:$reboot_cnt" > /dev/console
			nvram_set 2860 reboot_cnt $reboot_cnt

			if [ $reboot_cnt -gt 1 ]; then
				setled on
			else
				setled blink
			fi
			insmod dray_burn_in_test
		else
			# BLINK ACT LED
			setled act normal
		fi
	fi
}

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/run
	mkdir -p /var/log
	mkdir -p /var/lock
	mkdir -p /var/state
	mkdir -p /tmp/.uci
	chmod 0700 /tmp/.uci
	mkdir -p /tmp/.jail
	touch /var/log/wtmp
	touch /var/log/lastlog
	touch /tmp/resolv.conf.auto
	ln -sf /tmp/resolv.conf.auto /tmp/resolv.conf
	grep -q debugfs /proc/filesystems && /bin/mount -o noatime -t debugfs debugfs /sys/kernel/debug
	[ "$FAILSAFE" = "true" ] && touch /tmp/.failsafe

	dray_boot

	/sbin/kmodloader

	if [ "1" = "0" ]; then
		# allow wifi modules time to settle
		sleep 1

		/sbin/wifi detect > /tmp/wireless.tmp
		[ -s /tmp/wireless.tmp ] && {
			cat /tmp/wireless.tmp >> /etc/config/wireless
		}
		rm -f /tmp/wireless.tmp
	fi

	/bin/board_detect
	uci_apply_defaults
	
	# temporary hack until configd exists
	/sbin/reload_config

	# create /dev/root if it doesn't exist
	[ -e /dev/root -o -h /dev/root ] || {
		rootdev=$(awk 'BEGIN { RS=" "; FS="="; } $1 == "root" { print $2 }' < /proc/cmdline)
		[ -n "$rootdev" ] && ln -s "$rootdev" /dev/root
	}
}
