#!/bin/sh

cd $(dirname $0)

DEVICE=$1

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

BASE_CFG_TXT=./config_base.txt
BASE_CFG_BIN=./config_base.bin

rm -f $BASE_CFG_BIN

echo "========================================"
echo " Flash Write Start (BASE_CONFIG)"
echo "----------------------------------------"
echo " make base config "
echo "----------------------------------------"
if [ ! -f $BASE_CFG_TXT ]; then
    echo "[ERR] $BASE_CFG_TXT 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 $DEVICE
case $? in
0)
    MODE=0
    ;;
1)
    STATE=`./m3x_mainte br32 $DEVICE 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 $DEVICE
if [ $? -ge 2 ]; then
    exit 1
fi

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

echo "----------------------------------------"
echo " start sector erase "
echo "----------------------------------------"
./m3x_mainte flash $DEVICE sector_erase 0x00E00000 0x00040000
if [ $? -ge 2 ]; then
    ./m3x_mainte stop $DEVICE
    exit 1
fi

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

echo "----------------------------------------"
echo " stop flash function "
echo "----------------------------------------"
./m3x_mainte stop $DEVICE
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

exit 0
