#!/bin/sh

serial_init() {
  stty -F /dev/ttyO1 -crtscts speed 115200 rs485 rs485rtsonsend
}

can_init() {
  ip link set can0 up type can bitrate 500000
  ifconfig can0 up
}

firmware_update() {
    updateFileFound=0
    updateDone=0
    ufn=1
    
#Check if a timestamp file is exist and compare it with current time.
#If the current time is less than the update timestamp, skip the update
#If there is no timestamp file, then do the update
    for t in /root/updates/firmware/*.txt ; do
        if [ -e "$t" ]
        then
            activationTime=$(basename ${t%".txt"})
	        echo "Timestamp file $activationTime found!"
            now="$(date +"%s")"

            #Compare current timestamp to file timestamp and if current time is greater, then do the update
            if [ $now -lt $activationTime ]
            then
                echo "It is not time yet to do firmware update"
                return
            else
                echo "It is time now to do the firmware update"
                rm $t
            fi
	    fi
    done

    for f in /root/updates/firmware/vhcupdate_*.tar.gz ; do
        if [ -e "$f" ]
        then
            echo "Update file $f found!"
            updateFileFound=1

            cd /root/updates/firmware
            /bin/tar -xf $f

            updatedir=${f%".tar.gz"}

            if [ -d $updatedir ]
            then
                cd $updatedir
                echo "Current dir: $PWD"

                if [ -e "updatescript.sh" ]
                then
                    echo "Executing update..."
                    ./updatescript.sh
                    echo "Done executing update. Cleaning up!"

                    cd ../
                    rm -r $updatedir
                    rm $f 
                    updateDone=1
                else
                    echo "Update script not found!"
                fi
            fi
        fi

        if [ $updateDone -eq 1 ]
        then
            return
        fi
    done
}

serial_init
can_init

echo "************************** Invoking firmware update ***********************************************"
firmware_update


if [ $updateDone -eq 1 ]
then
    echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>Firmware update done, wait for power cycle >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
else
    cd /root/

    # The following are other app start-up methods, left here for reference.
    #/root/vhclfb -platform eglfs &
    #/root/vhclfb  -platform linuxfb -plugin tslib:/dev/input/event0  &
    #/root/vhclfb $masterFlag $orientation -platform linuxfb     -plugin tslib:/dev/input/event0 -plugin evdevkeyboard:/dev/input/event1 &

    # Now, start the vhc app

    echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Invoking application >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
    /root/vhclfb &
fi
