#!/bin/bash

PROGRAM=${0##*/}
SCRIPT_ROOT=$(dirname $(readlink -f "$0"))

if [ $# -ne 4 ]; then
	echo 'Usage: '$PROGRAM' loader uboot trust boot'
	exit -1
fi

cat /proc/cpuinfo |grep -E "Intel|AMD"
if [ $? -ne 0 ]; then
 echo "use arm version"
  LOG_DIR=~/.rockchip/upgrade_tool/aarch64/log
  CONFIG_INI=$SCRIPT_ROOT/aarch64_release/config.ini
  UPGRADE_TOOL=$SCRIPT_ROOT/aarch64_release/upgrade_tool
else
  LOG_DIR=~/.rockchip/upgrade_tool/x64/log
  CONFIG_INI=$SCRIPT_ROOT/x64_release/config.ini
  UPGRADE_TOOL=$SCRIPT_ROOT/x64_release/upgrade_tool
fi

mkdir -p $LOG_DIR
grep log_dir $CONFIG_INI > /dev/null
if [ $? -ne 0 ]; then
    echo "log_dir=$(realpath $LOG_DIR)" >> $CONFIG_INI
fi

LOADER=$1
UBOOT=$2
TRUST=$3
BOOT=$4
UBOOT_ADDR=0x20000
TRUST_ADDR=0x20800
BOOT_ADDR=0x21000

if [ ! -f $UPGRADE_TOOL ]; then
	echo $UPGRADE_TOOL 'is not existed!'
	exit -1
fi

if [ ! -f $LOADER ]; then
	echo $LOADER 'is not existed!'
	exit -1
fi

if [ ! -f $UBOOT ]; then
	echo $UBOOT 'is not existed!'
	exit -1
fi

if [ ! -f $TRUST ]; then
	echo $TRUST 'is not existed!'
	exit -1
fi

if [ ! -f $BOOT ]; then
	echo $BOOT 'is not existed!'
	exit -1
fi

echo 'start to wait device...'
i=0
while [ $i -lt 5 ]; do
	$UPGRADE_TOOL ld > /dev/null
	if [ $? -ne 0 ]; then
		i=$((i+1))
		echo $i
		sleep 0.01
	else
		break
	fi
done
if [ $i -ge 5 ]; then
	echo 'failed to wait device!'
	exit -1
fi
echo 'device is ready'

echo 'start to download loader...'
$UPGRADE_TOOL db $LOADER > /dev/null
if [ $? -ne 0 ]; then
	echo 'failed to download loader!'
	exit -1
fi
echo 'download loader ok'

echo 'start to wait loader...'
$UPGRADE_TOOL td > /dev/null
if [ $? -ne 0 ]; then
	echo 'failed to wait loader!'
	exit -1
fi
echo 'loader is ready'

echo 'start to write uboot...'
$UPGRADE_TOOL wl $UBOOT_ADDR $UBOOT > /dev/null
if [ $? -ne 0 ]; then
	echo 'failed to write uboot!'
	exit -1
fi
echo 'write uboot ok'

echo 'start to write trust...'
$UPGRADE_TOOL wl $TRUST_ADDR $TRUST > /dev/null
if [ $? -ne 0 ]; then
	echo 'failed to write trust!'
	exit -1
fi
echo 'write trust ok'

echo 'start to write boot...'
$UPGRADE_TOOL wl $BOOT_ADDR $BOOT > /dev/null
if [ $? -ne 0 ]; then
	echo 'failed to write boot!'
	exit -1
fi
echo 'write boot ok'

echo 'start to run system...'
$UPGRADE_TOOL rs $UBOOT_ADDR $TRUST_ADDR $BOOT_ADDR $UBOOT $TRUST $BOOT > /dev/null
if [ $? -ne 0 ]; then
	echo 'failed to run system!'
	exit -1
fi
echo 'run system ok'
