#!/bin/bash

cd "$(dirname "$0")"

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

RetCode=0

ITFSEND=./itfsend

clear
echo Linux Firmware Upload 1.0
echo
echo Update $FIRMWARE
echo
echo "1 - TCP-Port 9100 (<-Std)"
echo "2 - SSH/SCP"
echo "3 - Save SSH Passwd"


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 4 - TCP-Port 9100: $(<$TEMP/CV_UL_Last_TCP.tmp)
            DEFAULT=1
        fi
    else if (($LASTCHOICE == 2))
    then
        if [ -s $TEMP/CV_UL_Last_SSH.tmp ]
        then
            echo 4 - SSH/SCP: $(<$TEMP/CV_UL_Last_SSH.tmp)
            DEFAULT=1
        fi
    fi
    fi
fi

if [ $DEFAULT ]
then
    CHOICE=$(./bi "? " 4 [1234])
    if (($CHOICE != 4))
    then
        echo $CHOICE > $TEMP/CV_UL_Last_Itf.tmp
    fi
else
    CHOICE=$(./bi "? " [123])
    if (($CHOICE != 3))
    then
        echo $CHOICE > $TEMP/CV_UL_Last_Itf.tmp
    fi
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
    IPADDR=$(./bi "SSH IP? ")
    ./sshscp.sh $IPADDR "$FIRMWARE"
    echo $IPADDR > $TEMP/CV_UL_Last_SSH.tmp
else if (($CHOICE == 3))
then
    BOARDIP=$(./bi "SSH IP? ")    
    if [ ! -f "/home/$USER/.ssh/id_rsa" ]
    then
        mkdir -p "/home/$USER/.ssh"
        ssh root@"$BOARDIP" "exit"
        ErrCode=$?; if [ $ErrCode -ne 0 ]; then RetCode=$ErrCode; fi
        ssh-keygen
        ErrCode=$?; if [ $ErrCode -ne 0 ]; then RetCode=$ErrCode; fi
    fi
    ssh-keygen -f "/home/$USER/.ssh/known_hosts" -R "$BOARDIP"
    ErrCode=$?; if [ $ErrCode -ne 0 ]; then RetCode=$ErrCode; fi
    ./ssh-copy-id -i "/home/$USER/.ssh/id_rsa.pub" root@"$BOARDIP"
    ErrCode=$?; if [ $ErrCode -ne 0 ]; then RetCode=$ErrCode; fi
    if [ $RetCode -ne 0 ]; then
        read
    fi
else if (($CHOICE == 4))
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
    if (($LASTCHOICE == 2))
    then
        IPADDR=$(<$TEMP/CV_UL_Last_SSH.tmp)
        ./sshscp.sh $IPADDR "$FIRMWARE"
        echo $IPADDR > $TEMP/CV_UL_Last_SSH.tmp
    fi
fi
fi
fi
fi

sleep 2
