#!/bin/sh

PATH=/env/bin
export PATH

. /env/config
addpart /dev/mtd0 $mtdparts

usbserial -s "Mio A701 usb gadget"

gpio_get_value 22
is_usb_connected=$?

gpio_get_value 93
is_vol_up=$?

fb0.enable=1
# Phase1: Handle Vol-Up key case : drop immediately to console
if [ $is_vol_up != 0 ]; then
	console_mode
	exit
fi

# Phase2: Handle Power-On case : debounce PowerUp key or Halt
if [ $global.system.reset = "POR" -o $global.system.reset = "WKE" ]; then
	powerup_released=0

	gpio_get_value 0
	is_power_up=$?
	if [ $is_power_up = 0 ]; then
		powerup_released=1
	fi
	msleep 500

	gpio_get_value 0
	is_power_up=$?
	if [ $is_power_up = 0 ]; then
		powerup_released=1
	fi

	if [ $powerup_released = 1 ]; then
		echo "Power button not held, halting"
		poweroff
	fi
fi

# Phase3: display logo
led keyboard 0
splash /dev/mtd0.barebox-logo

# Phase4: check for SD Card override
sdcard_override
if [ $? = 0 ]; then
    console_mode
    exit
fi

# Phase5: check for MTD override
mtd_env_override
if [ $? = 0 ]; then
    echo "Switching to custom environment"
    /env/init
    exit
fi

# Phase6: check for user interrupting auto-boot
echo "No custom environment found"
if [ $is_usb_connected != 0 ]; then
	echo -n "Hit any key to stop autoboot: "
	timeout -a $autoboot_timeout
	if [ $? != 0 ]; then
		console_mode
		exit
	fi
fi

# Phase7: auto-boot linux kernel
echo "Booting linux kernel on docg3 chip ..."
bootm /dev/mtd0.kernel
