#!/bin/sh
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/home/mind/scripts

GPIODIR=/sys/class/gpio/gpio$GPIO
DESC="swupdate"
NAME="swupdate"
DAEMON=/usr/bin/swupdate
GPIO_RED=12
GPIO_GREEN=26
GPIODIR_RED=/sys/class/gpio/gpio$GPIO_RED
GPIODIR_GREEN=/sys/class/gpio/gpio$GPIO_GREEN

part=/dev/$1

systemctl stop swupdate
mount $part /mnt

rootfs=`mount | grep "on / type" | cut -d':' -f 2 | cut -d' ' -f 1`

if [ $rootfs == '/dev/mmcblk0p2' ];then
	selection="-e stable,mmcblk0p3"
else
	selection="-e stable,mmcblk0p2"
fi

echo "Starting $DESC ..."
echo "rootfs is mounted on $rootfs and selection is $selection"

# Parse /mnt for valid update files
highest_swu=$(get-latest-swu /mnt)
if [[  -z  $highest_swu  ]]; then
    echo "No valid .swu file found, quitting update task"
    umount /mnt
    exit 0
fi

echo "Update found:"
echo $highest_swu
sh -c 'notify-swupdate-start &'
swupdate -v ${selection} -i $highest_swu
if [ $? -eq 0 ]; then
	sync
	echo "swupdate-rpi-client: update done"
	killall notify-swupdate-start
	echo 0 > $GPIODIR_RED/value;
	echo 1 > $GPIODIR_GREEN/value;
else
	echo "swupdate-rpi-client: update failed"
	killall notify-swupdate-start
	echo 1 > $GPIODIR_RED/value;
	echo 0 > $GPIODIR_GREEN/value;
	umount /mnt
	echo "Restarting swupdate service..."
	systemctl start swupdate
	exit 1
fi

umount /mnt
exit 0
