#!/bin/sh
# fwupdate FILE... : flash images from Linux (no serial needed), then reboot.
# Partition is picked from the file name: app*.bin->APP dtb*->DTB kernel*->KERNEL
# rootfs*->ROOTFS config*->CONFIG data*->DATA, or say it explicitly: APP=/tmp/x.bin
# -n = don't reboot afterwards. Every block is read-back verified.
RB=-r; [ "$1" = -n ] && { RB=; shift; }
[ $# -gt 0 ] || { sed -n '2,6p' "$0"; exit 2; }
ARGS=
for a; do
    case "$a" in
        *=*) p=${a%%=*}; f=${a#*=} ;;
        *)   f=$a; case "$(basename "$f")" in
                app*) p=APP ;; dtb*) p=DTB ;; kernel*|uImage*) p=KERNEL ;;
                rootfs*) p=ROOTFS ;; config*) p=CONFIG ;; data*) p=DATA ;;
                *) echo "can't tell partition for $f (use PART=$f)"; exit 1 ;; esac ;;
    esac
    [ -f "$f" ] || { echo "no such file: $f"; exit 1; }
    ARGS="$ARGS $p $f"
done
# run the writer from RAM: APP (where we live) is about to be overwritten
cp /usr/sbin/mtdflash /tmp/mtdflash && chmod 755 /tmp/mtdflash || exit 1
touch /tmp/rtsp.stop; killall ak_rtsp_server_sample onvif_simple_server wsd_simple_server 2>/dev/null
echo 3 > /proc/sys/vm/drop_caches
exec /tmp/mtdflash $RB $ARGS
