#!/system/bin/sh
mode=$1
cmd=$2
usage()
{
    echo "Usage:"
    echo "mode_switcher [<options> ...] <command> [<arguments> ...]"
    echo "options:  normal                      return normal mode"
    echo "          factory                     reboot and factory test"
    echo "          recovery <command>          reboot recovery with command"
    echo ""
    echo "recovery commands:"
    echo "          --wipe_cache                wipe cache"
    echo "          --wipe_data                 factory reset, wipe data and cache"
    echo "          --update_package=<path>     update package"
    echo "                                      eg:--update_package=/mnt/external_sd/update.zip"
    echo ""
}

normal_mode()
{
    if [ ! "`mount |grep system_dir`" ] ; then
        umount /system_dir
    fi

    if [ ! "`mount |grep system`" ] ; then
        mount /dev/block/mtd/by-name/system /system/
    fi

    ./system/xbin/mtd erase misc

    cmd_file="/cache/recovery/command"

    if [ ! -f "$cmd_file" ] ; then
        rm -rf $cmd_file
    fi

    busybox reboot -f
}

factory_mode()
{
    cmd="--factory_test"
    cmd_dir="/cache/recovery"
    cmd_file="/cache/recovery/command"

    if [ ! "`mount |grep cache`" ] ; then
        mount /dev/block/mtd/by-name/cache /cache/
    fi

    if [ ! -f "$cmd_file" ] ; then
        mkdir -p $cmd_dir
        touch $cmd_file
    fi

    if [ -f "$cmd_file" ] ; then
        echo $cmd > $cmd_file
        reboot recovery
    fi
}

recovery_mode()
{
    if [ ! $cmd ]; then
        echo "command is NULL"
        usage
    else
        cmd_dir="/cache/recovery"
        cmd_file="/cache/recovery/command"

        if [ ! "`mount |grep cache`" ] ; then
            mount /dev/block/mtd/by-name/cache /cache/
        fi

        if [ ! -f "$cmd_file" ] ; then
            mkdir -p $cmd_dir
            touch $cmd_file
        fi

        if [ -f "$cmd_file" ] ; then
            echo $cmd > $cmd_file
            #reboot recovery
        fi
    fi
}

cancel_mode()
{
        if [ ! "`mount |grep cache`" ] ; then                                                   
            mount /dev/block/mtd/by-name/cache /cache/                                          
        fi
	
	if [ -f "$cmd_file" ] ; then                                                          
            rm -rf $cmd_dir                                                                   
        fi 		
}

set_recovery()
{
	mtd writechar "boot-recovery" misc
}

case $mode in
    normal)
        normal_mode
    ;;
    factory)
        factory_mode
    ;;
    recovery)
        recovery_mode
    ;;
    cancel)
	cancel_mode
    ;;
    set_recovery)
    	set_recovery		
    ;;
    *)
        usage
    ;;
esac




