#!/bin/bash

echo "NCast Digitizer 3 firmware update script, version 1.0."
echo ""

if [ $# -ne 1 ]; then
    echo "This script updates NCast Digitizer 3 firmware. You must run it as root."
    echo "Please remove digitizer3 kernel module before starting update process."
    echo ""
    echo "Synopsis: digitizer3update FIRMWARE_FILE"
    exit
fi

if [ $USER != "root" ]; then
    echo "You must run this scripts as root."
    exit
fi

DIGITIZER3_INSTALLED=`lsmod | grep digitizer | wc -l`
if [ $DIGITIZER3_INSTALLED != "0" ]; then
    echo "Please remove digitizer3 kernel module before starting update process."
    exit
fi

if [ ! -f $1 ]; then
    echo "Can't find firmware file $1."
    exit 1
fi

FIRMWARE=$1
echo "Updating to $FIRMWARE."

modprobe digiupdate

if [ $? = 1 ]; then
    echo "Error on inserting digiupdate kernel module."
else
    echo "Inserted digiupdate kernel module."
    
    STATUS=`cat /proc/digitizer_update`
    case $STATUS in
        "ERASE")
            echo "Firmware update is already running, driver is erasing flash."
            ;;
        "UPDATING")
            echo "Firmware update is already running, driver is uploading firmware."
            ;;
        "FAILURE" | "READY" | "SUCCESS")
            echo "Starting firmware update. Please wait."
	    
            echo "RESET_FOR_UPLOAD" > /proc/digitizer_update
	    
            STATUS2=`cat /proc/digitizer_update`
            if [ x$STATUS2 = "xREADY" ]; then
           		cat $FIRMWARE > /proc/digitizer_update
            	STATUS2=`cat /proc/digitizer_update`
           		if [ x$STATUS2 != x"SUCCESS" ]; then
                    echo "Firmware update failed. Trying again. Please wait."
                    # try to update again
                    rmmod digiupdate
                    sleep 2
                    modprobe digiupdate
                    sleep 2
                    cat $FIRMWARE > /proc/digitizer_update
                	STATUS2=`cat /proc/digitizer_update`
               		if [ x$STATUS2 != x"SUCCESS" ]; then
                        echo "Firmware update failed  (status $STATUS2)."
                    else
                        echo "Firmware update succeeded."
                    fi
                else
                    echo "Firmware update succeeded."
        	    fi
            else
           		echo "Unexpected error occured. Driver is not ready to upload firmware (status $STATUS2)."
            fi
	 
            rmmod digiupdate
            if [ $? = 1 ]; then
                echo "Error on removing digiupdate kernel module."
            fi
            ;;
        *)
       		echo "Unexpected error occured (status $STATUS)."
            ;;
    esac
fi
