#!/bin/bash

#1st Method (update using an usb stick)
#please edit the values with the appropriate one on your case
USB_DEVICE="/dev/sda"  
USB_MOUNT="/run/media/sda1"

#2nd Method (update using a 3rd partition on the SD card)
SDCARD_DEVICE="/dev/mmcblk0"
# Variables
NOR_DEVICE="/dev/mtd1"
EMMC_DEVICE="/dev/mmcblk1"
UBOOT_BIN="flash-kontron-mx6ul-2024.01-r0.bin"
WIC_IMAGE="image-ked-qt-kontron-mx6ul-0.0.0-dev.rootfs.wic.gz"
UBOOT_ENV="u-boot-initial-env-kontron-mx6ul-kontron-mx6ul-2024.01-r0"

# Check if the USB exists
if [ ! -e "$USB_DEVICE" ]; then
    echo "Device $USB_DEVICE not found!"
    exit 1
    # if no USB device found, use SD card instead
    # Check if the SD card exists
    if [ ! -e "$SDCARD_DEVICE" ]; then
        echo "Device $SDCARD_DEVICE not found!"
        exit 1
    else 
        mkdir -p /mnt/swupdate
        mount ${SDCARD_DEVICE}p3 /mnt/swupdate
        SW_UPDATE_SRC="/mnt/swupdate"
    fi
else
    SW_UPDATE_SRC=${USB_MOUNT}  
fi



# Flash U-Boot , ENV   
#erase nor flash before writing new data
flash_erase ${NOR_DEVICE} 0 0
# flash U-boot in u-boot NOR part /dev/mtd1
dd if=${SW_UPDATE_SRC}/${UBOOT_BIN} of=${NOR_DEVICE} bs=1k seek=1; sync   
echo "u-boot has benn flashed on NOR device (mtd1) successfully!"
# save the env-vars in env_redundant NOR part /dev/mtd3
fw_setenv -s ${SW_UPDATE_SRC}/${UBOOT_ENV} 
echo "u-boot environment has been saveed on env_redundant part (mtd3) successfully!"

# Unmount all partitions on the eMMC device
umount ${EMMC_DEVICE}p1
umount ${EMMC_DEVICE}p2
# erase eMMC flash using fdisk
# Launch fdisk to delete partitions
echo "Launching fdisk on $EMMC_DEVICE..."
fdisk $EMMC_DEVICE <<EOF
d
d
w
EOF
echo "eMMC flash has been erased".

# Flash WIC Image : 
gunzip -c ${SW_UPDATE_SRC}/${WIC_IMAGE} | dd of=${EMMC_DEVICE} bs=1M iflag=fullblock oflag=direct conv=fsync status=progress
echo "wic image flashed on eMCC device successfully!"
# Clean up
#umount /mnt/usbmount

echo "Flashing completed successfully!"
