#!/bin/bash

cd "$(dirname "$0")"

export TEMP=/tmp
export FIRMWARE=$(realpath ../../data.prn)

RetCode=0

ITFSEND=./itfsend

clear
echo Linux Data Upload 1.0
echo
echo Update $FIRMWARE
echo
echo "1 - TCP-Port 9100 (<-Std)"

if [ -s $TEMP/CV_UL_Last_Itf.tmp ]
then
    LASTCHOICE=$(<$TEMP/CV_UL_Last_Itf.tmp)
    if (($LASTCHOICE == 1))
    then
        if [ -s $TEMP/CV_UL_Last_TCP.tmp ]
        then
            echo 2 - TCP-Port 9100: $(<$TEMP/CV_UL_Last_TCP.tmp)
            DEFAULT=1
        fi    
    fi
fi

if [ $DEFAULT ]
then
    CHOICE=$(./bi "? " 1 [12])
    if (($CHOICE != 2))
    then
        echo $CHOICE > $TEMP/CV_UL_Last_Itf.tmp
    fi
else
    CHOICE=$(./bi "? " [1])
    echo $CHOICE > $TEMP/CV_UL_Last_Itf.tmp
fi

clear

if (($CHOICE == 1))
then
    IPADDR=$(./bi "TCP IP? ")
    $ITFSEND -d -r*9 -l -m1 -t -s$IPADDR < "$FIRMWARE"
    Errcode=$?
    if [ $Errcode -ne 0 ] && [ $Errcode -ne 250 ]; then
        echo $Errcode
        read
    fi
    echo $IPADDR > $TEMP/CV_UL_Last_TCP.tmp
else if (($CHOICE == 2))
then
    if (($LASTCHOICE == 1))
    then
        IPADDR=$(<$TEMP/CV_UL_Last_TCP.tmp)
        $ITFSEND -d -r*9 -l -m1 -t -s$IPADDR < "$FIRMWARE"
        Errcode=$?
        if [ $Errcode -ne 0 ] && [ $Errcode -ne 250 ]; then
            echo $Errcode
            read
        fi
        echo $IPADDR > $TEMP/CV_UL_Last_TCP.tmp
    fi
fi
fi

sleep 2
