#!/bin/bash


set -e
set -u

opwd=$PWD

handleError()
{
    echo "Error: Something went wrong here. $1"
    exit 22
}


cd /home/deseessm/obj/build-qhello-Desktop-Debug

month=$(date +"%m")
day=$(date +"%d")
year=$(date +"%y")


echo -n "Please enter serial number in hex without leading zeros (e.g. 0x123): "
read serial

serial=$(printf '0x%x\n' $serial)
serialLong=$(printf '%08X\n' $serial)

# echo -n "Please enter variant in hex without leading zeros (e.g. 0x123): "
# read serial
variant=0

if [ -z "$serial" ]; then hanleError "You did not specify an serial number."; fi


echo << EOF > gdb.txt

br loop
run
call (flash)(10,\"mmm\")
clear loop
c
EOF

a=$(nm qhello | grep myStruct)
addr=${a%% *}

echo "Will try x/20xb 0x$addr"

cat << EOF >gdb.txt

br main:loop
run
set var \$new = (SMyStruct *)malloc(sizeof(struct SMyStruct))
set var \$new.version = 1
set var \$new.name="Script"
set var \$new.day=$day
set var \$new.month=$month
set var \$new.year=$year
set var \$new.serial=$serial
call (writeHwInfo)(\$new)

# target reset run
print/x bringupFirmware

set logging file serial.txt
set logging overwrite
set logging on
print/x myStruct.serial
set logging off


set logging file all.txt
set logging overwrite
set logging on
print/x myStruct
print &myStruct
x/32xb \$0
set logging off

EOF

gdb qhello -x gdb.txt -batch-silent -q || handleError "Could not write HwInfo. Is bringup firmware flashed?"


echo -e "\n"

echo "Serial: "
a=$(cat serial.txt)
isSerial="${a##* = }"

if [ "$serial" == "$isSerial" ]; then
    cat all.txt
    echo "Serial is OK; $serial == $isSerial"
else
    handleError "Serial is NOT OK; $serial != $isSerial"
fi

mv all.txt $opwd/hwinfo_${serialLong}.txt


#cat << EOF > gdb.txt
#br main:loop
#run
#set logging file serial.txt
#set logging overwrite
#set logging on
#print/x myStruct.serial
#set logging off
#clear loop
#EOF
#gdb qhello -x gdb.txt -batch-silent -q



#---fin------------------------------------------------------------------------
