#!/bin/sh
# Copyright (c) 2014-2019 Algo Communication Products Ltd.

usage()
{
	cat <<EOF
Usage: $0 url
  url: http or ftp URL to the firmware image file
EOF
}

if [ "$#" -lt "1" ]; then
	usage
	exit 1
fi

URL=$1
DLPATH=/opt/algo/upgrade
DLSTAT=/var/run/download.status
mkdir -p $DLPATH
cd $DLPATH
rm -f *.sfw $DLSTAT
wget $URL
if [ $? -ne 0 ]; then
	echo "Failed to download firmware file." > $DLSTAT
	rm -f *.sfw
	exit
fi

FWNAME=$(basename $URL)
/opt/algo/bin/check-firmware $DLPATH $FWNAME
if [ $? -ne 0 ]; then
	echo "Invalid firmware." > $DLSTAT
	rm -f *.sfw
	exit
fi

if ! grep nosyschk /run/algo-upgrade.flag 2>/dev/null; then
	/opt/algo/bin/check-sysreq $DLPATH $(basename $URL) $DLSTAT
	if [ $? -ne 0 ]; then
		rm -f *.fw
		exit
	fi
fi

echo "finished" > $DLSTAT
/opt/algo/bin/upgrade-firmware -w $DLPATH $(basename $URL)
