#!/bin/sh

DESC="IOCU firmware"

INSTALLED_IOCU_FILE="/data/version_iocu"
# Content can be 1 (partition1) or 2 (partition2)

FAULTED_IOCU_INSTALLATION="/data/iocu_faulted"

IOCU_PATH="/data/config"
IOCU_FILE="firmware.hex"


p1=`cat /proc/cmdline | grep ubi.mtd=3 | wc -l`
p2=`cat /proc/cmdline | grep ubi.mtd=4 | wc -l`

INSTALL_RETRY=0

start() {
    echo "start"
    if [ -f $INSTALLED_IOCU_FILE ];
    then
        # File exist
        INSTALLED_IOCU_VERSION=`cat "$INSTALLED_IOCU_FILE"`
        if [ "$INSTALLED_IOCU_VERSION" == "1" ] && [ $p2 -gt 0 ] && [ $p1 = 0 ];
        then
            echo "Running P2 and iocu installed is of P1. Install IOCU..."
            install 2
        elif [ "$INSTALLED_IOCU_VERSION" == "2" ] && [ $p1 -gt 0 ] && [ $p2 = 0 ];
        then
            echo "Running P1 and iocu installed is of P2. Install IOCU..."
            install 1
        fi

    else
        # File does not exist
        if [ $p2 -gt 0 ] && [ $p1 = 0 ];
        then
            echo "Running P2. Install IOCU..."
            install 2
        elif [ $p1 -gt 0 ] && [ $p2 = 0 ];
        then
            echo "Running P1. Install IOCU..."
            install 1
        fi
    fi
    echo "done"
}
stop() {
    echo "stopped"
}
restart() {
    start
}
install(){
    echo "Install... Execute P$1, retry$INSTALL_RETRY"
    IOCU_FIRMWARE="$IOCU_PATH/$1/$IOCU_FILE"
    if [ -f $IOCU_FIRMWARE ];
    then
        # file exist
        echo 0 > /sys/class/mx28ccu/iocu/reset/value && sleep 1 && echo 1 > /sys/class/mx28ccu/iocu/reset/value
        avrdude -C /etc/avrdude.conf -p x32a4u -P /dev/ttyAPP0 -c avr109 -b 115200 -U flash:w:$IOCU_FIRMWARE:i -e
        OUT=$?
        if [ $OUT -ne 0 ];
        then
            # Output is not 0. Something went wrong while flashing
            echo "Install firmware: Applying new firmware faulted"
            if [ $INSTALL_RETRY -lt 10 ];
            then
                INSTALL_RETRY="$((INSTALL_RETRY + 1))"
                install $1
            else
                echo "Install firmware; Failed after retries. Stop trying"
                touch $FAULTED_IOCU_INSTALLATION
            fi
        else
            echo $1 > $INSTALLED_IOCU_FILE
            rm -f $FAULTED_IOCU_INSTALLATION
        fi
    else
        echo "IOCU_FIRMWARE file does not exist..."
    fi

}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart|reload)
        restart
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac

exit $?

