#!/bin/sh

led_gr () {
    echo $1 > /sys/class/leds/dora:green:led/brightness
    echo $2 > /sys/class/leds/dora:red:led/brightness
}

if [ "$#" != 0 ]; then
	echo USAGE: update-net http://example.com/updater.tgz 2>&1
	exit 1
fi

if ! ln -s / /tmp/update-net; then
	echo Other update-net is running 2>&1
	exit 0
fi

header=/tmp/update-net-header
trap "umount /tmp/u;rm -rf /tmp/update-net /updater $header;sync" EXIT
trap "trap '' INT; kill -INT  0;notify 1;exit 130" INT
trap "trap '' TERM;kill -TERM 0;notify 1;exit 143" TERM

notify () { vsclient updater-status "$@"; }
mkdir -p /updater
url=${1:-https://livewedge.cerevo.com/static/firmware/updater.bin}
if [ -n "$url" ]; then
	# notify 10
	# clife check_firmware
	# notify 11 if error
	notify 20
	led_gr 1 1
	curl -fD $header "$url" > /updater/updater.tgz
	es=$?
	if [ $es != 0 ]; then
		case $es in
			6)  notify 21 ;; # resolv
			7)  notify 22 ;; # connect
			22) notify 24 ;; # 404 or other
			23) notify 25 ;; # disk full
			*)  notify 26 ;;
		esac
	elif grep -iq ^location: $header; then
		notify 23	# redirect
		led_gr 0 1
	else
		notify 30
		mkdir -p /tmp/u
		mount none /tmp/u -t tmpfs -o size=40m
		tar zxC /tmp/u < /updater/updater.tgz
		es=$?
		sync
		if [ $es != 0 ]; then
			led_gr 0 1
			notify 31
		else
			notify 40
			if ! /tmp/u/update; then
				led_gr 0 1
				notify 41
			else
				led_gr 1 0
				notify 0
				trap - EXIT INT TERM
				umount /tmp/u
				sync; sync; sync
				sleep 1
				exec reboot
			fi
		fi
	fi
fi
