#!/bin/sh

cd $(dirname $0)

WRITE_ALL=$2

if [ -z "$WRITE_ALL" ]; then
  WRITE_ALL=0
fi

BASE=../01_M30_firm/base_fw.bin
BASE_CFG_TXT=./config_base.txt
BASE_CFG_BIN=./config_base.bin

rm -f $BASE_CFG_BIN

echo "========================================"
echo " Flash Write Start (BASE FW)"
echo "----------------------------------------"
echo " make base fw "
echo "----------------------------------------"
if [ ! -f $BASE_CFG_TXT ]; then
    echo "[ERR] $BASE_CFG_TXT file not found."
    exit 1
fi

if [ ! -f $BASE ]; then
    echo "[ERR] $BASE file not found."
    exit 1
fi

./m3x_config_base $BASE_CFG_TXT > /dev/null
if [ $? -ge 1 ]; then
    exit 1
fi

echo "success"

echo "----------------------------------------"
echo " check mode "
echo "----------------------------------------"
./m3x_mainte check 1
case $? in
0)
    MODE=0
    ;;
1)
    STATE=`./m3x_mainte br32 0 0 0x02000200`
    if [ $? -ge 2 ]; then
        exit 1
    fi

    if [ "`echo $STATE | grep -e "=> 0x00000003" -e "=> 0xFFFFFFFF"`" ]; then
        echo ""
        echo "<< Need to change the MCPU to boot/initial state >>"
        echo ""
        exit 1
    fi

    MODE=1
    ;;
*)
    exit 1
    ;;
esac

echo "----------------------------------------"
echo " load flash function "
echo "----------------------------------------"
./m3x_mainte boot 0
if [ $? -ge 2 ]; then
    exit 1
fi

./m3x_mainte load 0 flash
if [ $? -ge 2 ]; then
    ./m3x_mainte stop 0
    exit 1
fi

echo "----------------------------------------"
echo " start chip erase "
echo "----------------------------------------"
./m3x_mainte flash 0 chip_erase
if [ $? -ge 2 ]; then
    ./m3x_mainte stop 0
    exit 1
fi

echo "----------------------------------------"
echo " start program "
echo "----------------------------------------"
echo "Writing ${BASE##*/}... "
./m3x_mainte flash 0 program 0x00000000 $BASE
if [ $? -ge 2 ]; then
    ./m3x_mainte stop 0
    exit 1
fi

echo "Writing ${BASE_CFG_BIN##*/}... "
./m3x_mainte flash 0 program 0x00E00000 $BASE_CFG_BIN
if [ $? -ge 2 ]; then
    ./m3x_mainte stop 0
    exit 1
fi

if [ $WRITE_ALL -eq 0 ]; then
    echo "----------------------------------------"
    echo " stop flash function "
    echo "----------------------------------------"
    ./m3x_mainte stop 0
    if [ $? -ge 1 ]; then
        exit 1
    fi
    
    echo "----------------------------------------"
    echo " program end "
    echo "========================================"
    
    if [ $MODE -eq 1 ]; then
        echo ""
        echo "<<                   Need to restart the host PC                    >>"
        echo "<< It is also possible to restart after updating the other firmware >>"
        echo ""
    fi
fi

exit 0
