1#!/bin/bash
2
3BACKUP_IFS=$IFS
4IFS=$(echo -en "\n\b")
5
6function dir_with_file() {
7    local file=${1}; shift
8    local dir;
9    for dir; do
10        if [ -z "${dir}" ]; then continue; fi
11        if [ -r "${dir}/${file}" ]; then
12            echo ${dir}
13            return
14        fi
15    done
16    echo "Could not find ${file}, looked in $@" >&2
17    return 1
18}
19
20LOCAL_DIR=$(dirname "${0}")
21
22# Location of where the Brillo OS image is built.
23UBOOT_DIR=$(dir_with_file u-boot-edison.img \
24    "${LOCAL_DIR}"/uboot_firmware \
25    "${LOCAL_DIR}")
26IFWI_DIR=$(dir_with_file edison_dnx_fwr.bin \
27    "${LOCAL_DIR}"/ifwi_firmware \
28    "${LOCAL_DIR}")
29
30if [ $? -ne 0 ]; then
31    exit 1
32fi
33
34GETOPTS="$(which getopt)"
35if [[ "$OSTYPE" == "darwin"* ]] ; then READLINK=greadlink; GETOPTS="$(brew list gnu-getopt | grep bin/getopt)"; else READLINK=readlink;fi;
36
37if [[ "$OSTYPE" == "cygwin" ]] ;
38then
39	TEMP_DIR="$(dirname $($READLINK -f "$0"))"
40	UBOOT_DIR="$(cygpath -m ${UBOOT_DIR})"
41	IFWI_DIR="$(cygpath -m ${IFWI_DIR})"
42else
43	UBOOT_DIR=${UBOOT_DIR//' '/'\ '}
44	IFWI_DIR=${IFWI_DIR//' '/'\ '}
45fi;
46
47LOG_FILENAME="flash.log"
48
49function print-usage {
50	cat << EOF
51Usage: ${0##*/} [-h][--help]
52Update all software and restore board to its initial state.
53 -h,--help     display this help and exit.
54EOF
55	exit -5
56}
57
58function flash-debug {
59	echo "DEBUG: lsusb"
60	lsusb
61}
62
63function flash-ifwi {
64	if [ -x "$(which xfstk-dldr-solo)" ]; then
65		flash-ifwi-xfstk
66	else
67		echo "!!! You should install xfstk tools, please visit http://xfstk.sourceforge.net/"
68		echo "!!! Alternatively, see the Edison-Brillo web for information on using Phone Flash Tool Lite"
69		exit -1
70	fi
71}
72
73function flash-ifwi-xfstk {
74	XFSTK_PARAMS=" --gpflags 0x80000007 --osimage ${UBOOT_DIR}/u-boot-edison.img"
75	XFSTK_PARAMS="${XFSTK_PARAMS} --fwdnx ${IFWI_DIR}/edison_dnx_fwr.bin"
76	XFSTK_PARAMS="${XFSTK_PARAMS} --fwimage ${IFWI_DIR}/edison_ifwi-dbg-00.bin"
77	XFSTK_PARAMS="${XFSTK_PARAMS} --osdnx ${IFWI_DIR}/edison_dnx_osr.bin"
78
79	eval xfstk-dldr-solo ${XFSTK_PARAMS}
80	if [ $? -ne 0 ];
81	then
82		echo "Xfstk tool error"
83		flash-debug
84		exit -1
85	fi
86}
87
88# Execute old getopt to have long options support
89ARGS=$($GETOPTS -o hv -l "recovery,help" -n "${0##*/}" -- "$@");
90#Bad arguments
91if [ $? -ne 0 ]; then print-usage ; fi;
92eval set -- "$ARGS";
93
94while true; do
95	case "$1" in
96		-h|--help) shift; print-usage;;
97		--) shift; break;;
98	esac
99done
100
101echo "** Flashing Edison Board $(date) **" >> ${LOG_FILENAME}
102
103
104if [[ "$OSTYPE" == "darwin"* ]] ; then
105	echo "Recovery mode is only available on windows and linux";
106	exit -3
107fi
108
109echo "Starting Recovery mode"
110echo "Please plug and reboot the board"
111echo "Flashing IFWI"
112flash-ifwi
113echo "Recovery Success..."
114echo "You can now try a regular flash"
115
116IFS=${BACKUP_IFS}
117