#!/bin/sh

kill_all_apps()
{
    # Kill any of our apps from /app/bin folder that are running
    ALLAPPS=$(ls /app/bin)
    killall ${ALLAPPS} 
    killall -9 ${ALLAPPS} 
}

watchdog_off()
{
    # Make sure watchdog is off
    echo 1 > /dev/watchdog
    sleep 1
    echo V > /dev/watchdog
}

#Check is this firmware is compatible with this device
anti_brick_check()
{
    # Get the product id and serial from OTP
    PRODUCTID=$(printf "%d" $(cat /sys/fsl_otp/HW_OCOTP_GP1))

    # Get the software update targetNumber from the info.xml
    targetNumber=-1
    if [ -f ${USBROOTPATH}/info.xml ]; then
	targetNumber=$(sed -n 's/.*<targetNumber>\(.*\)<\/targetNumber>/\1/p' $USBROOTPATH/info.xml)
    	#targetNumber=$(xmllint --xpath "string(//softwareInfo/targetInfo/targetNumber)" $USBROOTPATH/info.xml)
    fi

    echo "Running on Product ${PRODUCTID}, firmware update target: ${targetNumber}"
    if [ ${PRODUCTID} -ne ${targetNumber} ]; then
	echo ERROR DURING UPDATE, INCOMPATIBLE SOFTWARE!

	fbv -s 1 ${USBROOTPATH}/recovery/bitmaps/recoveryIncompatibleFirmware.png
	#setup_usb_eject_script    
	exit_error 300
    fi
}

backlights_full()
{
    # Turn LCD backlights full on
	echo 0 > /sys/class/pwm/pwmchip2/export
	echo 100000 > /sys/class/pwm/pwmchip2/pwm0/period
	echo 1 > /sys/class/pwm/pwmchip2/pwm0/enable
	echo 100000 > /sys/class/pwm/pwmchip2/pwm0/duty_cycle
}

display_updating()
{
    fbv -s 1 ${USBROOTPATH}/recovery/bitmaps/${PRODUCTID}/recoveryupdating.png
}

# Check we have all the app files we require
app_validate()
{
    echo App: Validating...

    # Does the directory for the app exist?
    if [ ! -d ${USBROOTPATH}/root ]; then
        exit_error 200
    fi

    # Check we have all the required files
    APPFILES="root.tar.bz2"
    for APPFILE in ${APPFILES}
    do
        if [ ! -f ${USBROOTPATH}/root/${APPFILE} ]; then
            echo App: ${USBROOTPATH}/root/${APPFILE} not found!
            exit_error 201
        fi
    done
}

# Update the app
app_update()
{
    echo "App: Removing partitions..."
    ubirmvol /dev/ubi0 --name=data
    ubirmvol /dev/ubi0 --name=app
    
    echo "App: Creating partitions..."
    ubimkvol /dev/ubi0 --name=app --size=${APPPARTSIZEMB}MiB
    ubimkvol /dev/ubi0 --name=data --maxavsize
    
    echo "App: Mounting partitions..."
    mkdir -p /tmp/root/app
    mount -t ubifs ubi0:app /tmp/root/app
    mkdir -p /tmp/root/app/data
    mount -t ubifs ubi0:data /tmp/root/app/data

#    restore_data

    echo "App: Updating..."
    cd /tmp/root
    tar jxf ${USBROOTPATH}/root/root.tar.bz2
    
    # Permissions
    chown -R 0:0 /tmp/root/*
    chmod -R 755 /tmp/root/*

    # Copy etc overlay on to /etc
    mount -o remount,rw /
    
    cp -ar /tmp/root/* /

    mount -o remount,ro /
    
    sync

    echo "App: Updating splashscreen..."
    if [ -f "${USBROOTPATH}/app/splashscreen${PRODUCTID}.bmp" ]; then
        # Platform dependent splashscreen supplied outside root.tar.bz2
        SPLASHSCREEN=${USBROOTPATH}/app/splashscreen${PRODUCTID}.bmp
    elif [ -f "${USBROOTPATH}/app/splashscreen.bmp" ]; then
        # Generic splashscreen supplied outside app.tar.bz2
        SPLASHSCREEN=${USBROOTPATH}/app/splashscreen.bmp
    elif [ -f "/tmp/root/app/bin/splashscreen${PRODUCTID}.bmp" ]; then
        # Platform dependent splashscreen supplied inside app.tar.bz2
        SPLASHSCREEN=/tmp/root/app/bin/splashscreen${PRODUCTID}.bmp
    else
        # Generic splashscreen supplied inside app.tar.bz2
        SPLASHSCREEN=/tmp/root/app/bin/splashscreen.bmp
    fi
    mkimage -A arm -O linux -T kernel -C none -a 0 -e 0 -n "splashscreen" -d ${SPLASHSCREEN} /tmp/splashscreen.bmpu > /dev/null
    flash_eraseall /dev/mtd4
    nandwrite -p /dev/mtd4 /tmp/splashscreen.bmpu
    rm /tmp/splashscreen.bmpu

    # Dismount and detach UBI
    cd /tmp
    umount /tmp/root/app/data
    umount /tmp/root/app
    rm -rf /tmp/root
}

# Successful update
exit_success()
{
    echo "exit_success"
    #fbv -s 1 ${USBROOTPATH}/recovery/bitmaps/${PRODUCTID}/recoveryupdatesucceeded.png
    echo SUCCESSFUL UPDATE!
    
    /app/bin/DeviceUpdateDaemon --programSucceeded	

    sleep 5
    echo "reboot"
    reboot
    
    exit 0
}

# Error during update
exit_error()
{
    echo "exit_error $1"
    if [ "$1" -ne 300 ]; then
	#Display recovery update error unless it is an incompatible firmware (code 300)
	fbv -s 1 ${USBROOTPATH}/recovery/bitmaps/${PRODUCTID}/recoveryupdateerror.png
    fi
    echo ERROR $1 DURING UPDATE!

    /app/bin/DeviceUpdateDaemon --programFailed	

    sleep 5
    reboot
    
    exit $1
}

read_settings()
{
    # Set default settings
    APPPARTSIZEMB=${APPPARTSIZEDEFAULTMB}
    KEEPOLDDATA="N"
    RESTOREOLDDATA="N"

    echo "Extracting settings.sh to /tmp..."
    cd /tmp
    tar jxf ${USBROOTPATH}/root/root.tar.bz2 app/bin/settings.sh
    chmod 755 /tmp/app/bin/settings.sh
    # and import the settings (the above defaults may get overriden)
    source /tmp/app/bin/settings.sh
    rm -rf /tmp/app
}

###############################################################################

# Main entry point of script

echo "Running canUpdate.sh..."

# Redirect output to debug serial
#exec 1>/dev/ttymxc0
#exec 2>/dev/ttymxc0

# Get path of this script file (/tmp/usbupdate)
SCRIPTPATH=$(cd ${0%/*} && echo ${PWD%/*})
USBROOTPATH=$SCRIPTPATH

echo "usbupdate path: $USBROOTPATH"

ARSMODE=1

kill_all_apps

watchdog_off

#Check firmware compatibility
anti_brick_check

# The default APP partition size
APPPARTSIZEDEFAULTMB=128

backlights_full

display_updating

#firmware_validate
app_validate


# Its only the app that needs updating   
read_settings

# Dismount UBI partitions and detach
    umount /app/data
    umount /app/event
    umount /app

app_update
    
exit_success

