#!/bin/sh
PATH=/usr/local/bin:$PATH
HOME=/usr/local/root

while :; do echo > /dev/watchdog; sleep 30; done &
PID_WDT=$!

fpga-config /usr/local/share/fpga.ttf &
PID_FPGA=$!

gkf_get () {
	awk 'BEGIN{r=1}/^\[/{x=0}/^\['$2']/{x=1}(x)&&/^ *'$3' *=/{sub("^ *'$3' *= *", "");print;r=0}END{exit r}' $1 2>/dev/null
}

run_autorun() {
    local readonly sd=/media/mmcblk0p1
    local readonly uid=999
    local readonly gid=999
    local readonly d=$(sed -n '/DEVICETYPE=/s/DEVICETYPE=//p' /usr/local/share/fw.ini)
    local readonly autorun=autorun_${d}
    local readonly rev=$(sed -n '/App Revision: /s/App Revision: //p' /etc/ustbox_version)
    local run

    run=$(gkf_get ~/.cerevo.ini SWITCH AUTORUN) || run=0
    [ ${run} -ne 1 ] && return 0
    if [ -x ${sd}/${autorun} ]; then
	(sleep 30
	    mounted --request-rw || return 1
	    [ -d ${sd}/etc ] || mkdir ${sd}/etc
	    [ -f ${sd}/etc/resolv.conf ] || touch ${sd}/etc/resolv.conf
	    mount -o bind /etc/resolv.conf ${sd}/etc/resolv.conf
	    clife adjust_time
	    unset USER
	    unset HOME
	    unset PATH
	    unset TERM
	    unset SHELL
	    DEVICETYPE=${d} FIRMWARE_REVISION=${rev} \
		/usr/local/bin/chroot_setuid ${uid} ${gid} ${sd} /${autorun} 127.0.0.1
	    /bin/umount ${sd}/etc/resolv.conf
	    /usr/local/bin/mounted --request-ro
	)&
    fi
}

check_key_detect () {
	local i=$(ub300key)
	i=${i%% *}
	if [ $((i&1)) != 0 ]; then
		ifup-eth eth0 ether
		update-net && exec reboot
	elif [ $((i&2)) != 0 ]; then
		update-sd && exec reboot
		ub300key -wheel | while read k i; do [ $k -eq 0 ] || break; done
	elif [ $((i&4)) != 0 ]; then
		test-hdmi
		test-phase 1
		ifconfig eth0 0.0.0.0
		test-mac
	fi
}

ifconfig lo up
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -F
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
echo 82368  109824  164736  > /proc/sys/net/ipv4/tcp_mem
echo 4096   16384   3514368 > /proc/sys/net/ipv4/tcp_wmem
sysctl -w net.ipv4.tcp_timestamps=0
davincifb /dev/fb1 backg 1 0 1
fbblank /dev/fb0 1 /dev/fb1 0 /dev/fb2 1
wait $PID_FPGA

check_key_detect
killall glcdd
while ps|grep -q '[g]lcdd'; do sleep .1; done
vsui
run_autorun
while :; do
	switch &
	PID_SWITCH=$!
	mount | grep -q /dev/mmcblk0p1 && while ! mounted; do sleep .5; done
	wait $PID_SWITCH
done
kill $PID_WDT
wait $PID_WDT
echo -n V > /dev/watchdog
