#!/bin/bash

# Usage: flash-fw-usb sub1-01 /home/firefly/Firmware/android.img

set -uo pipefail

CACHE_DIR=/var/netrecovery
FLASH_RATE=$((5 * 1024 * 1024))  # estimated 5MB/s

. /usr/share/bmc/lib.sh

usb_flash() {
    local statedir rc_file
    statedir=${CACHE_DIR}/$node/state
    rc_file=${statedir}/upgrade_tool.rc

    node_report_status $node $JOB_PREPARING 10 "switching to loader"
    __switch_to_loader() {
      node_switch_to_loader $node || :
      sleep 1
      is_loader_device $node
    }
    retry_cmd 3 10 __switch_to_loader \
          || node_error_with_exit_code $node $ELOADER "switch to loader failed"

    node_report_status $node $JOB_PREPARING 100 "waiting to flash"
    wait_meeting_flashing_limit

    monitor() {
        local fw_size=$(stat -c '%s' $firmware) progress=0 delay rc
        delay=$(python3  -c "print('%.3f' % ($fw_size / $FLASH_RATE / 100.0))")
        while [[ ! -f $rc_file ]]; do
            node_report_status $node $JOB_FLASHING $progress
            sleep $delay
            ((progress+=1))
            ((progress >= 100)) && progress=99
        done
        rc="$(cat $rc_file)"
        if [[ "$rc" = 0 ]]; then
            progress=100
            node_report_status $node $JOB_FLASHING $progress
            sleep 6
            node_report_status $node $JOB_DONE
        else
            node_report_status $node $JOB_ERROR $rc "upgrade_tool failed"
        fi
    }
    rm -f $rc_file &>/dev/null || :
    monitor &
    monitor_pid=$!

    # Use upgrade_tool to flash firmware
    local location_id="" rc
    node_adb_get_usb "$node" location_id
    location_id="${location_id#usb:}"
    location_id="${location_id//[-.]/}"
    upgrade_tool -s $location_id ef $firmware
    upgrade_tool -s $location_id uf $firmware -noreset
    rc=$?
    echo $rc >$rc_file
    node_reset $node

    wait $monitor_pid
    return $rc
}

if (( $# < 2 )); then
  error_with_exit_code $EUSAGE "Usage: flash-fw-usb <node> <firmware>"
fi

node="$1"
firmware="$2"
id="${3:-$$}"

check_node "$node"
check_firmware "$firmware"
usb_flash
