#!/bin/bash

set -e

fw="${1}"

dut-control servo_console_pty
dut-control ec_uart_pty
dut-control cpu_uart_pty

[ -z "$fw" ] && exit 0

echo "* reset"
dut-control cold_reset:off
sleep 1
dut-control cold_reset:on
sleep 1

echo "* vref on"
dut-control spi2_vref:pp1800 spi2_buf_en:on
sleep 1

echo "* fw_wp"
dut-control fw_wp_en:on
dut-control fw_wp:off
dut-control fw_up:on
dut-control fw_wp_en
dut-control fw_wp
dut-control fw_up
sleep 1

echo "* erase"
sudo flashrom --programmer raiden_debug_spi -E

echo "* read dump.bin"
sudo flashrom --programmer raiden_debug_spi -r "dump.bin"

echo "* flash [$fw]"
sudo flashrom --programmer raiden_debug_spi -w "$fw"

echo "* vref off"
dut-control spi2_vref:off spi2_buf_en:off
sleep 1

echo "* reboot"
dut-control cpu_uart_en:on
dut-control dev_mode:on
sleep 1
dut-control cpu_uart_en
dut-control dev_mode
dut-control cold_reset:off
dut-control dev_mode:on
sleep 1
dut-control dev_mode

exit 0
